Python uses indentation to mark blocks of statements, so whitespace can affect program meaning rather than only appearance.
Understanding the Concept
A block follows constructs such as if, for, while, and def. A colon introduces a suite in the usual multiline style, and the following lines must be indented consistently. Four spaces per level is the customary style. Blank lines and extra spaces around operators generally improve readability but do not start blocks by themselves. Mixing tabs and spaces inconsistently can cause TabError or confusing code structure.
When and Why You Would Use This
The program below checks a condition and prints one line inside the block, then another outside. Compare their indentation and predict which statements run when the condition is false.
Practical Example
has_ticket = True
if has_ticket:
print("You may enter")
print("Check complete")
Understanding the Example
With True, both lines print. If has_ticket becomes False, only Check complete prints. The indentation places the first print inside the condition but leaves the second outside it.
Example Output
You may enter
Check complete
Try It Yourself
Change has_ticket to False and predict the output. Then deliberately remove four spaces to observe the error before restoring them.
Common Beginner Mistakes
- Removing indentation after an if statement and triggering IndentationError.
- Using visually similar tabs and spaces inconsistently.
- Believing a blank line ends a Python block rather than indentation change.
Key Takeaways
- Indentation defines code blocks in Python.
- Use a consistent four-space indentation style.
- A statement outside an indented block may run even when the block is skipped.