Python Indentation

  • Indentation in python refers to spaces and tabs that are used at the beginning of the statement
  • Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
  • The statement with the same indentation belongs to same group called a suite.
  • This it is used to create or represent a block of code

  • Python uses indentation to indicate a block of code.

if 5 > 2:

  print ("Five is greater than two!")
  • Python will give you an error if you skip the indentation:

if 5 > 2:

print ("Five is greater than two!")

here we will get syntax error due to non-indentation

  • The number of spaces is up to you as a programmer, but it has to be at least one.

if 5 > 2:
 print ("Five is greater than two!")

if 5 > 2:
        print ("Five is greater than two!")
  • You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:
if 5 > 2:

 print ("Five is greater than two!")

        print ("Five is greater than two!")

Comments in python

Python has commenting capability for the purpose of in-code documentation. Comments start with a #, and Python will render the rest of the line as a comment:

#This is a comment.

print ("Hello, World!")
  • Comments can be used to explain Python code.
  • Comments can be used to make the code more readable.
  • Comments can be used to prevent execution when testing code.

To add a multiline comment, you could insert a # for each line:

Using Triple Quotes (Multiline String):

Enclose your comment text within triple quotes (”’ or “””). Python treats everything between these triple quotes as a single string, effectively ignoring it during execution.

Example:

'''
This is a multiline comment.
It spans multiple lines.
Python will ignore these lines when executing the code.
'''
print ('Hello, World!')
Scroll to Top