Python Syntax Rules & Indentation
Python uses indentation (whitespace) to define code blocks — unlike other languages that use curly braces {}. Getting indentation right is mandatory. This topic covers Python's unique syntax rules.
Python Syntax Rules
- Indentation is MANDATORY — defines code blocks (4 spaces)
- No semicolons needed at end of lines
- No curly braces {} — indentation replaces them
- Colons : mark the start of a new block (if:, for:, def:)
- Case-sensitive — name, Name, NAME are all different
- Backslash \ for line continuation
- Parentheses () also allow multi-line expressions
- IndentationError — most common Python error for beginners
Indentation Examples
# Correct indentation (4 spaces)
age = 20
if age >= 18:
print("You are an adult") # 4 spaces in
print("You can vote") # same level
else:
print("You are a minor") # 4 spaces in
# Nested indentation
for i in range(3):
print(f"Outer: {i}") # 4 spaces
for j in range(2):
print(f" Inner: {j}") # 8 spaces
# Line continuation
total = (100 +
200 +
300)
print("Total:", total) # 600
# Multi-line with backslash
message = "Hello " + \
"World " + \
"Python"
print(message)Tip
Tip
Configure your editor to insert 4 spaces when you press Tab. In VS Code: Settings → Editor: Tab Size → 4, and enable Editor: Insert Spaces. This prevents IndentationError forever.
Everything in Python is an object — use type() to check
Common Mistake
Warning
Mixing tabs and spaces causes IndentationError. Python 3 doesn't allow mixing. Always use spaces (4 per level). If you copy code from the web, it might have tabs — convert them.
Practice Task
Note
Indentation exercise: (1) Write an if/else with proper 4-space indentation. (2) Write a nested if inside a for loop (8 spaces). (3) Try removing indentation and read the error message.
Quick Quiz
Key Takeaways
- Python uses indentation (whitespace) to define code blocks — unlike other languages that use curly braces {}.
- Indentation is MANDATORY — defines code blocks (4 spaces)
- No semicolons needed at end of lines
- No curly braces {} — indentation replaces them