Statement, Indentation and Comments in python

Python Statement

Instructions that a Python interpreter execute are called statements. For example, x = 1 is an assignment statement. pass statement ,if statement, for statement, while statement etc.

Multi-line statement

A statement extend over multiple lines with the line continuation character (\). For example:

a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
This is explicit line continuation. In Python, line continuation is implied inside parentheses ( ), brackets [ ] and braces { }. For instance, we can implement the above multi-line statement as

a = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)
Here, the line continuation happens implicitly. Same is the case with [ ] and { }. For example:
Code = ['R', 'G', 'B']
We could also put multiple statements in a single line using semicolons, as follows
a = 1; b = 2; c = 3

Python Indentation

Python uses indentation to define block e.g body of a function, class ,loop etc. starts with indentation and ends with the first unindented line. Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example.
for i in range(1,11): print(i) if i == 5: break
The enforcement of indentation in Python makes the code look neat and clean. This results into Python programs that look similar and consistent. Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes the code more readable.

Python Comments

Comments allows to describe the code details that might help for reading/ enhancing or debuuging the code.

  • In Python, hash (#) symbol is used for writing a comment.
  • It extends up to the newline character.
  • Comments enhaces the readability of a program.
  • Python Interpreter ignores comment.
#This is a comment #print out Hello print('Hello')
Multi-line comments If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of each line. For example:
#This is a multiline comment #and extended #to multiple lines

We can also use triple quotes, either ''' or """ for multi line comments. These triple quotes are generally used for multi-line strings. But they can be used as multi-line comment as well. Unless they are not docstrings, they do not generate any extra code.

"""This is an example of multi-line comments"""

Docstring is short for documentation string. It is a string that occurs as the first statement in a module, function, class, or method definition. The docstring describes what a function/class does in the docstring. Triple quotes are used while writing docstrings. For example:

def Mulitply(num1,num2): """Function to multiply the values""" return num1 * num2 #Docstring is available through the attribute __doc__ of the function. >>> print(Multiply.__doc__) Function to Multiply the values