Python Indentation and Comments

Table of contents

Python Indentation and Code Blocks

If you are familiar with other programming languages such as C, C++, or Java, you must be aware that they use braces { } to define blocks of code. However, Python strictly enforces the use of indentation to mark a block of code. Using indentation as a block marker makes code clear and consistent.

For example:

for i in range(0, 10):
    if i%2 == 0:
        print(i, "is even.")
        print(i, "is odd.")

As seen in the example above, blocks can also be nested within other blocks. ‘if’ and ‘else’ are two separate blocks nested within the ‘for’ block. Similarly, statements print(i, ‘is even.’) and print(i, ‘is odd.’) are part of ‘if’ and ‘else’ blocks respectively as they are indented within them. However, statement print(“Goodbye!”) is not indented within the ‘for’ block so it is not part it. Python generates IndentationError in case of incorrect indentation.

It doesn’t matter how many spaces or tabs you use to indent but all the statements within the block must have the same number of whitespaces. The PEP8 standard recommends using 4 whitespaces.

Python Comments

Including comments to programs make it easy for you or other developers to understand the source code and fix bugs in the future. Comments are ignored by the python interpreter and are helpful to a person reading the code to know the context of the program.

How to write comments in Python?

Python allows two ways to write comments to a program. They are single-line comments and multi-line comments.

Single-line Comments

In Python, single-line comments can be added by writing hash # character followed by a comment. The single-line comment is terminated by the end of the line.

For example:

#This is a single-line comment
#hello world program
print('Hello world')

In the above example, the first two lines start with # so they are ignored by the python interpreter.

Multi-line comments

The single-line comment only extends until the newline. That is why we had to start both of the lines in the above example with #. In cases when comments need to be extended multiple lines, we can either start each line with # or start and end multiple lines with quotes, either “”” or ”’.

For example:

"""This is a multi-line comment and 
can be extended to multiple lines. 
hello world program""" 
print('Hello world')