Python Programming Syntax

1. Python Comment

# symbol is used for comment in python. In most editors keyboard shortcut to comment/uncomment is Ctrl + /. However, Python IDLE uses Alt + 3 to comment and Alt + 4 to uncomment.

x = 10 # this is a commment

2. Semicolon in Python Syntax

; exists in Python with the same meaning of line termination or line seperation. However, \n is more frequently used for line termination.

x = 0
y = "Programink"

3. Multiple assignment

It is possible to assign multiple variable to multiple values respectively in python.

x, y, z = 1, 2.3, "hello"

4. Swapping

Multiple assignment makes swapping very easy in Python and a temporary variable is never needed.

x, y = y, x

5. Case sensitive

Python is case-sensitive language and changes in case results into a new object.

>>> 'a' == 'A'

6. Use of quotes in python

Quotes are used in python to define string objects. There are four categories of quotes that can be used:

'a' == "a" == '''a''' == """a"""

7. Use of backslash

\can be prefixed before special characters to treat them as normal characters.


8. Nomenclature

Naming identifiers in Python must obey these rules:

  • It must consist of only A-Za-z0-9_
  • It must not begin with digits 0-9
  • It must not be a keyword. import keyword; print(keyword.kwlist)
x1 = "hello" # valid
3m = "hello" # invalid

9. Indentation

A simple left padding also acts as block definition in Python. It is typically a tab space in the beginning.

def greeting():
    print("Welcome to Programink")

10. Underscore '_'

_ is used in multiple different ways in python.

  • In interactive mode underscore _ refers to the last computed values.
  • One underscore _ in the beginning of variable name indicates that the variable will become private later on.
  • Two underscores __ before an attribute name makes it private.
  • Two underscores on either side of attribute name symbolizes weak attribute and it is read as 'dunder'. Eg. __name__
>>> x = 10
>>> _ + 1