Indentation in Python

Let us look at your last post on social media. No, not your own post, but your comment on your favourite influencer’s post. How are the comments aligned? For better understanding, the original post starts at the beginning of the line. The first comment starts a few spaces away from the original post. If you reply to a comment, your reply will stack under the comment.

That shows that these replies are associated with this comment, not the main post. This is how the indentation works.

If a code is under another line of code, you have to indent it to show Python that it is under that one. We will take an if statement as an example:

In this statement, we want to run the third line only if the condition we are setting is True. That is, the third line will depend on the second line. That means we must indent it once:

price = 400
if price < 500:
    print ("I will buy the phone")

If you don’t indent that line, you will get an error. That is because Python does not know what to do if the condition is True.

If there will be more than one line under that if statement, you have to give all the lines the same indentation.

price = 400
if price < 500:
    print ("I will buy the phone")
    print ("She will be happy")

Just like in writing English, we call indentation a paragraph. In coding, we call it a code block. A code block will have more than one line.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials