Course contentsShow
← Python
Lesson 9 of 1,0601. Foundations and EnvironmentFree lesson

Understanding Python Indentation and Code Blocks

You will master the use of consistent whitespace to define code structure and logical blocks instead of using traditional curly braces.

Mastering Python’s Visual Logic: Indentation

In this lesson, you will learn how Python uses consistent whitespace to define its structure, replacing the curly braces {} found in many other programming languages.

The Power of the "Block"

In most languages, programmers use curly braces to group lines of code together into a "block"—a logical unit that should execute together (like the instructions inside an if statement). In Python, we use indentation (the empty space at the start of a line) to tell the interpreter exactly where a block begins and ends.

Think of it like an outline for an essay: every sub-point is indented further to the right than the main point. Python expects you to do the same.

Putting it into Practice

Take a look at this simple example:

# The line below defines a condition
if 5 > 2:
    # This line is indented by 4 spaces
    print("Five is indeed greater than two!")
    print("This line is also inside the block.")

# This line has no indentation, so it's back in the main flow
print("This prints regardless of the condition.")

The Golden Rules of Indentation

To keep your code readable and bug-free, follow these two rules:

  1. Consistency is Key: You can choose to use two spaces or four spaces to indent, but you must be consistent throughout your entire file. The Python community standard is four spaces. Never mix tabs and spaces, as this will cause an IndentationError.
  2. The Colon Matters: Notice the colon : at the end of the if statement. That colon is Python’s way of saying, "The next lines are the beginning of a block, so please indent them."

If you forget to indent, Python won't know which instructions belong to your logic block, and it will stop your program from running. Think of your indentation as the "scaffolding" that holds your code together—if the scaffolding is crooked, the structure won't stand!

Key Takeaway: In Python, indentation is not just for style; it is mandatory syntax that defines how your code is organized and executed.