Python - Syntax & Indentation
Overview
Estimated time: 25–35 minutes
Learn how Python uses indentation to define blocks, how to write statements and expressions, and best practices for readable code.
Learning Objectives
- Use indentation to structure code blocks correctly.
- Differentiate expressions vs statements; write simple statements properly.
- Follow basic style (PEP 8) for consistent, readable code.
Prerequisites
Indentation defines blocks
x = 3
if x > 0:
print("positive")
if x > 2:
print("greater than two")
print("done")
Expected Output:
positive
greater than two
done
Expressions vs statements
# statement:
y = 10
# expression:
result = (y + 5) * 2
print(result)
Expected Output: 30
Common Pitfalls
- Mixing tabs and spaces. Use 4 spaces per indent; configure your editor.
- Misaligned blocks cause IndentationError or logic errors.
Checks for Understanding
- How many spaces per indentation level are recommended by PEP 8?
- What error do you get when indentation is inconsistent?
Show answers
- Four spaces.
IndentationError
Exercises
- Write a nested if block with two levels and print different messages.
- Reformat code that uses tabs into spaces and ensure it still runs.