Python Indentation
 

Python Indentation

 

An indentation or indent is an empty space at the beginning of a line that signals the start of a new logical block in a Python program. Many programming languages such as c and c++ uses curly braces to describe a block of code, indentation used just for readability in them.

Indentation is very important in Python and other programming languages that use this technique.

Example of using indentation in Python

The following example shows the use of indentation in Python if-else statements.

num=10
if num>=5:
     print("The given number is greater than 5")
elif num==5:
     print("The given number is equal to 5")
else:
     print("The given number is less than 5")

As you can see the highlighted part in the image below, shows the use of indentation in Python code.

Python IndentationError

All the code in Python is arranged with the use of correct whitespaces. When no indentation is used where it required or if not used in a correct way, the Python interpreter will through IndetationError.

Now if we run the above code in the following way –

num=10
if num>=5:
print("The given number is greater than 5")
elif num==5:
     print("The given number is equal to 5")
else:
     print("The given number is less than 5")

This will through IndentationError, you can see this in the image below.

Whenever you use encounter this error, check whether you have used whitespaces correctly before a line of code.

How many spaces you should use?

The number of spaces that you use before a line of code is up to you but you should use at least one whitespace. Remember to use the same number of spaces before each line of code that falls in the same block of code.

Conclusion

This is all about the use of indentation in Python. Now if you have a query then write use in the comments below.

Previous Taking Input From Users In Python
Next Python if else and nested if else statements
 

About author

You might also like

Python Programming 0 Comments

Python Dictionary Data Type

Python dictionary is an unordered collection of data values it stores data in key:value pairs. A pair of braces i.e. {} without any value creates an empty dictionary. You can

Python Programming 0 Comments

Using Python pass keyword

The Python pass keyword which is a statement in itself basically does nothing. It can be used as a placeholder for future code. As empty code is not allowed in

Programming 0 Comments

Python program to check whether a number or string is palindrome or not

A number or string is said to be a palindrome if its reverse is the same as the given number or string. For example – Malayalam is a palindrome string

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Reply