Lines and Indentation in Python

Python uses indentation instead of braces to define blocks of code. Unlike languages such as C++ or Java, Python relies on consistent spacing to group statements together for functions, classes, and control structures.

Basic Indentation Rules

All statements within a block must be indented with the same number of spaces. The Python convention is to use 4 spaces per indentation level ?

if True:
    print("True")
else:
    print("False")
True

Inconsistent Indentation Error

Python will raise an IndentationError when statements in the same block have different indentation levels ?

if True:
    print("Answer")
        print("True")  # Error: inconsistent indentation
else:
    print("Answer")
    print("False")

This code generates an IndentationError because the second print statement has different indentation than the first.

Nested Blocks Example

Here's a complete example showing multiple levels of indentation ?

def process_numbers():
    numbers = [1, 2, 3, 4, 5]
    
    for num in numbers:
        if num % 2 == 0:
            print(f"{num} is even")
            if num > 2:
                print(f"{num} is greater than 2")
        else:
            print(f"{num} is odd")
    
    print("Processing complete")

process_numbers()
1 is odd
2 is even
3 is odd
4 is even
4 is greater than 2
5 is odd
Processing complete

Key Points

  • Use 4 spaces per indentation level (PEP 8 standard)
  • Never mix tabs and spaces
  • All statements in the same block must have identical indentation
  • Indentation defines code structure and flow control

Common Indentation Patterns

Structure Indentation Level Example
Top level 0 spaces def function():
Function body 4 spaces if condition:
Nested block 8 spaces print("nested")

Conclusion

Python's indentation-based syntax enforces clean, readable code structure. Always use consistent 4-space indentation and avoid mixing tabs with spaces to prevent syntax errors.

Updated on: 2026-03-25T07:27:43+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements