Why does python need to recognize blocks of code with indentation?

The Question: I am just starting out with Python. I was reading on Python indentation. I have understood that Python indentation is there so Python can recognize blocks of code. My question is why does it need to recognize those blocks of code anyway? Other languages don’t have it (as far as I have read on that article, not all languages show error if you accidently don’t use tabs or same amount of spaces for the same block of code)

That’s the way the designers chose to make Python. The indentation is a part of the syntax and provides logical information

I am not an expert of programming language, but as far as I know, programming languages which do not require indentation use some markers, such as brackets to indicate the beginning and the end of blocks of code. Python does not use marker to denote the end of a code block, so indentation is the only mean to let the interpreter program know where is the end of a code block.

1 Like

I’m just beginning Python myself and one tip I picked up is that the syntactically-required four-space indentation can be deferred to the TAB key in most code editors in the settings (if it’s not already set by default). If you use TAB without this being explicitly set though, you may run into trouble!

Let’s see an example. When using a for loop, the indentation indicates which lines of codes belong to the loop and to be repeated. Codes like this:

for i in range(3):
    print('Hello')
    print('Joyeta')

will get this output:

Hello
Joyeta
Hello
Joyeta
Hello
Joyeta

But in this code which the last line does not indented:

for i in range(3):
    print('Hello')
print('Joyeta')

The last line is not regarded as part of the loop, and only execute once:

Hello
Hello
Hello
Joyeta

1 Like

Thank you so much, now I have better understanding on the topic.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.