Repaso
EspaƱol
PythonFoundationsPY-65

How does Python know which lines belong inside an if or a loop?

Options

  1. With curly braces { }, like in Java or JavaScript
  2. With indentation: lines indented the same amount form one block (Correct option)
  3. With semicolons at the end of every line in the block
  4. 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 runs

Remember

Python blocks = colon + indentation.

Key terms

Practice this question in Repaso