Python Syntax & Indentation Rules (PEP 8)

๐Ÿ Python 3 ๐ŸŸข Lesson 4 of 12 ๐Ÿ“‚ Phase 1: Python Basics ๐Ÿ“… 2026 Edition
Master whitespace indentation, why Python uses indentation instead of curly braces, avoiding IndentationError, and following PEP 8 coding standards.
1The Significance of Indentation in Python

In languages like C, Java, and JavaScript, code blocks (bodies of functions, if-statements, loops) are enclosed inside curly braces { }. In Python, code blocks are defined entirely by whitespace indentation.

A colon : indicates the start of a block, and every subsequent statement inside that block must be indented consistently (standard is 4 spaces).

2Correct Indentation vs IndentationError
# โœ… CORRECT INDENTATION (4 spaces) if score >= 90: print("Grade: A") print("Excellent work!") # โŒ INCORRECT (Causes IndentationError) if score >= 90: print("This will crash immediately!")
3PEP 8 โ€” The Official Python Style Guide
  • Use 4 spaces per indentation level (do not mix tabs and spaces).
  • Limit lines to 79 characters for readability.
  • Use lowercase with underscores for variable and function names: user_name, calculate_total().
  • Use CamelCase for class names: UserAccount, DatabaseConnection.
๐Ÿ’ป Complete Executable Code Example
# Indentation in Control Flow Blocks
temperature = 28

if temperature > 30:
    print("It's a hot sunny day! โ˜€๏ธ")
    print("Stay hydrated.")
elif temperature > 20:
    print("The weather is pleasant and warm. ๐ŸŒค๏ธ")
    print("Perfect time for a walk.")
else:
    print("It is cool outside. ๐Ÿงฅ")

print("Program execution finished.")
โš ๏ธ Common Pitfall: Mixing Tabs and Spaces

Mixing tab characters and space characters in the same block causes TabError. Configure your editor to automatically convert tabs to 4 spaces.

๐Ÿ’ป Try It Yourself โ€” Hands-on Practice Challenge

Observe how nested blocks (loops inside if statements) use multiple levels of 4-space indentation.

numbers = [12, 15, 20, 25, 30]

print("Filtering even numbers greater than 15:")
for num in numbers:
    # Level 1 indentation (4 spaces)
    if num % 2 == 0:
        # Level 2 indentation (8 spaces)
        if num > 15:
            # Level 3 indentation (12 spaces)
            print(f"  -> Found: {num}")
Run This Code in Our Online Compiler โ†’
โ“ Frequently Asked Questions (FAQ)

Q: Why did Python choose indentation over curly braces?

Indentation enforces clean, uniform formatting across all Python codebases, making code written by anyone easy to read and maintain.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026