How does Python know which lines belong inside an if or a loop?
Options
- With curly braces { }, like in Java or JavaScript
- With indentation: lines indented the same amount form one block (Correct option)
- With semicolons at the end of every line in the block
- With the words BEGIN and END around the block
Answer
With indentation: the block is the group of lines indented the same amount (usually 4 spaces)
Why
Many languages (Java, JavaScript) use { } for blocks. Python uses indentation, so the layout is part of the grammar.
The line before an indented block ends with a colon :.
If you mix tabs and spaces or indent wrongly, Python raises an IndentationError.
if age >= 18:
print("adult") # inside the if
print("welcome") # also inside
print("done") # outside, always runsRemember
Python blocks = colon + indentation.