Mastering Python's Indentation and Scope
In this lesson, you will learn how to use whitespace to define which lines of code belong to your conditional statements.
Unlike many other programming languages that use curly braces { } to group code, Python relies entirely on indentation. In Python, a "code block" is a group of statements that run together under a specific condition. To tell Python that a line of code belongs inside an if, elif, or else statement, you must indent it further to the right than the header line.
The Power of the Indent
Take a look at this example:
age = 20
if age >= 18:
print("Welcome!") # This line is inside the block
print("Access granted.") # This line is also inside the block
print("Goodbye!") # This line is outside the block
In the code above, the two print statements are indented by four spaces. This tells Python: "Only run these lines if the condition age >= 18 is true." Once you stop indenting (returning to the original margin), Python knows the block has ended, and the print("Goodbye!") will execute regardless of the age.
Common Pitfalls
The most common error for beginners is an IndentationError. This happens if you fail to indent after a colon (:) or if you mix tabs and spaces. PEP 8—which we covered in an earlier lesson—recommends using four spaces for each level of indentation.
If you don't indent consistently, your logic will fail. If you indent a line that shouldn't be part of the condition, your code might run, but it won't perform the task you intended. Think of indentation as the "fence" that keeps your code logic organized; everything inside the fence is protected by the if statement, and everything outside proceeds normally.
Always check that your lines align perfectly within their blocks. If you are starting a new block after a condition, make sure every line inside that block has the exact same amount of indentation.
Key Takeaway: Indentation is the structural foundation of Python; it defines where your code blocks begin and end, so keeping your spaces consistent is essential for your program to run correctly.