Python Indentation

Python uses indentation to define blocks of code, making it an essential part of writing Python programs. Proper indentation ensures that Python can identify the scope of loops, conditionals, functions, and other control structures.



What You'll Learn

You will learn how to properly indent your Python code, avoid common indentation errors, and understand the role of indentation in defining code blocks in Python.


Understanding Python Indentation

In Python, indentation defines which code belongs to loops, functions, conditionals, and other structures. It is crucial for the program's flow and readability.

The basic rules of indentation:

  • Indentation is required after statements like: `if`, `for`, `while`, `def`, `class`.
  • Use spaces (4 spaces per indentation level) rather than tabs.
  • Maintain consistency: Use either spaces or tabs, but not both in the same file.
  • Indentation defines the scope of code blocks, so it’s vital for logic flow.

Here’s an example of correct indentation:

python
if x > 10:
    print("x is greater than 10")
    print("This is inside the 'if' block")
print("This is outside the 'if' block")

Note: Don’t worry about `if`, `else`, or functions for now. We will introduce these concepts in upcoming topics. For now, just focus on understanding how indentation works.


Example 1: Basic Indentation with If-Else

The following example demonstrates basic indentation with `if-else` statements:

python
x = 10

if x > 5:
    print("x is greater than 5")
else:
    print("x is 5 or less")

How It Works:

StatementDescription
x = 10This sets the variable x to 10.
if x > 5:The `if` condition checks whether x is greater than 5. If the condition is true (which it is, since x = 10), the indented code block directly under `if` is executed.
Indentation after the `if` statement:In Python, after a statement like `if`, you must indent the next line to indicate that it belongs to the `if` block. This indentation is usually 4 spaces (or a tab, but spaces are recommended). If the condition is true, Python executes the indented code below `if`.
print("x is greater than 5")This line is indented by 4 spaces, indicating that it is part of the `if` block. It will print "x is greater than 5" because the condition is true.
else:The `else` statement is aligned with the `if`, and the code under `else` is indented to show that it is part of the `else` block. It runs if the `if` condition is false.
Indentation after the `else` statement:Similar to the `if`, the code inside the `else` block must also be indented. It is essential to maintain the same level of indentation (4 spaces) under `else` to signify that the code belongs to the `else` block.
print("x is 5 or less")This line is also indented by 4 spaces, which means it belongs to the `else` block. This line would only be executed if the condition in the `if` statement were false.

Output

x is greater than 5

Example 2: Indentation in Loops

Loops like `for` and `while` also require indentation to define the loop's scope:

python
for i in range(3):
    print("Iteration:", i)
    print("This line is inside the loop")
print("This line is outside the loop")

How It Works:

StatementDescription
for i in range(3):This line defines the loop. The loop will run 3 times, as `range(3)` generates the numbers 0, 1, and 2. The code block inside the loop will be executed for each iteration of `i`.
Indentation after the `for` statement:In Python, after a loop statement like `for`, you must indent the code that should be executed in each iteration of the loop. This indentation is usually 4 spaces (or a tab, but spaces are recommended). Any code indented below `for` will be repeated for each iteration.
print("Iteration:", i)This line is indented by 4 spaces, which means it is part of the loop body. The line will be executed 3 times, once for each value of `i` (0, 1, and 2).
print("This line is inside the loop")This line is also indented by 4 spaces, so it is inside the loop. It will be printed during every iteration.
Indentation after the loop:After the loop ends, the indentation level should return to its previous state, indicating that the next statement is outside the loop. This means that the `print("This line is outside the loop")` statement will execute only once after the loop finishes.
print("This line is outside the loop")This line is not indented, so it is outside the loop. It will only execute once, after the loop finishes running.

Output

Iteration: 0
This line is inside the loop
Iteration: 1
This line is inside the loop
Iteration: 2
This line is inside the loop
This line is outside the loop

Example 3: Indentation in Functions

The following example demonstrates indentation inside a Python function:

python
def greet():
    print("Hello, world!")

greet()  # Calling the function

How It Works:

StatementDescription
def greet():This line defines a function named `greet`. The colon `:` at the end indicates the start of the function's body, which will be indented.
Indentation after the `def` statement:In Python, after a function definition (using `def`), you must indent the next lines to indicate that they belong to the function’s body. This indentation is usually 4 spaces (or a tab, but spaces are recommended). All code inside the function must be indented consistently.
print("Hello, world!")This line is indented by 4 spaces, showing that it belongs to the `greet` function. When the function is called, this line will be executed, and the message "Hello, world!" will be printed.
greet()This line calls the function `greet`. Since this line is not indented, it is outside the function definition. When executed, it will invoke the `greet` function, triggering the indented print statement within the function.

Output

Hello, world!

Exercises

Try the following exercises to practice Python indentation:

1. Fix the Indentation Error in the following code:
python
x = 7
if x > 5:
print("x is greater than 5")

2. Write a program that prints the numbers 1 to 5 using a `for` loop. Make sure the code inside the loop is properly indented.
python
for i in range(1, 6):
    print(i)

3. Create a function called `is_even` that checks if a number is even and prints a message accordingly. Ensure proper indentation inside the function.
python
def is_even(number):
    if number % 2 == 0:
        print("Even")
    else:
        print("Odd")

*Tip: Practice proper indentation and experiment with different control structures and loops to get comfortable with Python syntax!


Frequently Asked Questions

Why is indentation important in Python?

Python uses indentation to define blocks of code. Unlike many other programming languages that use curly braces or keywords, Python relies on whitespace to group statements. Incorrect indentation can lead to errors or unexpected behavior.


How many spaces should I use for indentation?

The Python style guide (PEP 8) recommends using 4 spaces per indentation level. It's important to be consistent throughout your code and avoid mixing tabs and spaces.


What happens if I don't indent my Python code properly?

Improper indentation in Python will result in an IndentationError or cause your code to behave incorrectly. Since indentation defines the structure and scope of code blocks, even a small misalignment can break your program.


Can I use tabs instead of spaces for indentation?

Technically, yes—but it's strongly recommended to use spaces. PEP 8 suggests using 4 spaces per level of indentation. Mixing tabs and spaces can cause confusing bugs, especially in larger codebases or when collaborating with others.


Is indentation only required after certain statements?

Yes. Indentation is mandatory after control statements like if, else, for, while, def, and class. These statements expect a block of code to follow, and that block must be indented.


How do I fix indentation errors in Python?

Make sure that all blocks of code are properly aligned. Use a code editor that highlights indentation and set it to insert 4 spaces instead of tabs. You can also enable "Show invisibles" or "Render whitespace" to visually spot inconsistent indentation.


Does indentation affect performance or just readability?

Indentation primarily affects the structure and logic of your code, not performance. However, it plays a critical role in readability and maintainability, which are essential for debugging and collaboration.



What's Next?

Next, you'll learn about Python's control flow structures like `if-else`, loops, and functions, which will help you create more dynamic programs.