Python Syntax & Indentation
Line Statements
Python statements end at the newline character rather than a semicolon, so a print("hi") line is complete the moment the line ends — no trailing punctuation required. You can still use a semicolon to cram two statements onto one line, but it's rarely idiomatic Python.
Example: Line Statements
print("hi")
print("no semicolon needed")
print("a"); print("b")
Indentation Rules
Where C-family languages use { } to group statements into a block, Python uses consistent indentation instead — the interpreter parses whitespace as structural syntax, not just cosmetic formatting. Getting this wrong doesn't just look messy, it changes which code belongs to which if, loop, or function.
Example: Indentation Rules
if True:
print("Indented block belongs to the if")
print("Back to outer level")
Block Structure
All statements at the same indentation level are treated as one block belonging to whatever if, loop, or function opened it; the block ends the moment a line returns to a shallower indent. Mixing indentation depths within what should be one block raises an IndentationError rather than silently misgrouping code.
Example: Block Structure
if True:
print("first line of block")
print("second line, same indent")
print("outside the block")
Multi-line Statements
A trailing backslash \ at the end of a line tells Python the statement continues on the next line, useful for breaking up a long expression so it stays readable without exceeding a sensible line length. Expressions already inside parentheses, brackets, or braces can also wrap across lines without needing a backslash at all.
Example: Multi-line Statements
total = 1 + 2 + \
3 + 4
print(total)
total2 = (1 + 2 +
3 + 4)
print(total2)
Syntax Errors
The two most common indentation mistakes are mixing tabs and spaces (which can look identical in an editor but differ to the interpreter) and forgetting to indent a new block after a colon. Configuring your editor to insert spaces for the Tab key sidesteps the first problem entirely.
Example: Syntax Errors
# Common mistakes:
# 1. Mixing tabs and spaces in the same block
# 2. Forgetting to indent after a colon
if True:
print("correctly indented")
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: