Python Syntax
1. Python Comment
The # symbol is used for comments 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 comment
2. Semicolon In Python Syntax
; exists in Python with the same meaning of line termination or line separation. However, \n is more frequently used for line termination.
>>> a = 1; b = 2
>>> a, b = 1, 2
3. Multiple Assignments
It is possible to assign multiple variables to multiple values respectively in python.
>>> x, y, z = 1, 2.3, "hello"
>>> a = b = c = 0
4. Swapping
Multiple assignments make swapping very easy in Python and a temporary variable is never needed.
>>> x, y = y, x
5. Case Sensitive
Python is a case-sensitive language and changes in case results into a new object.
>>> 'a' == 'A'
False
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"""
True
>>> '''INSERT INTO TABLE VALUES("John's Car")'''
>>> """ Multi-line
string
"""
7. Use Of Backslash
\ can be prefixed before special characters to treat them as normal characters.
'C:\\Users\\Programink\\Desktop'
\ can also be used for line continuation.
>>> x = 1 + 2 \
3
>>> x
6
8. Nomenclature
Naming identifiers in Python must obey these three rules:
1) It must consist of only A-Za-z0-9_
2) It must not begin with any digit 0-9
3) It must not be a keyword. To check the keywords run:
>>> import keyword
>>> print(keyword.kwlist)
>>> x1 = "hello" # valid
>>> 3m = "hello" # invalid
9. Indentation
Simple left padding acts as a block definition in Python. It is typically a tab space or four white space in the beginning of an enclosed statement.
def greeting():
print("Welcome to Programink")
10. Underscore '_'
_ is used in multiple different ways in python.
a) In interactive mode underscore _ refers to the last computed values.
b) One underscore _ at the beginning of the variable name indicates that the variable will become private later on.
c) Two underscores __ before an attribute name makes it private.
d) Two underscores on either side of the attribute name symbolize weak attribute and it is read as 'dunder'. Eg. __name__
>>> x = 10
>>> _ + 1
11