🏗️ Python Code Structure

Python has a unique way of organizing code that makes it easy to read and write. Unlike languages that use curly braces {}, Python uses indentation (spaces) to group code together. This makes Python programs look clean and forces good coding habits from the start.

Understanding Python's structure rules is essential—Python is very particular about how code is organized, but once you learn the rules, they become natural and make your code more readable.

# Python code structure basics
print("Python code is clean and organized!")

# Indentation groups code together
if True:
    print("This line is indented")
    print("This line is also indented")
    
print("This line is back to the main level")

# Functions also use indentation
def greet(name):
    print(f"Hello, {name}!")
    print("Welcome to Python!")

greet("Programmer")

📐 Indentation: Python's Unique Feature

Indentation is Python's way of grouping code together. While other languages use curly braces {}, Python uses spaces at the beginning of lines to show which code belongs together.

Key Indentation Rules:

  • 4 spaces is the standard (recommended by PEP 8)
  • All lines in the same block must have identical indentation
  • Never mix tabs and spaces in the same file
  • Use either tabs OR spaces consistently (spaces preferred)
# Indentation examples
print("=== INDENTATION EXAMPLES ===")

name = "Alice"
age = 25

# Code block with indentation (4 spaces)
if age >= 18:
    print(f"{name} is an adult")
    print("They can vote")
    
    # Nested indentation (8 spaces total)
    if age >= 21:
        print("They can also drink")
        
print("Back to main level (no indentation)")

🔗 Code Blocks and Colons

Code blocks are groups of statements that work together. In Python, you create code blocks using:

  1. A colon (:) at the end of the line that starts the block
  2. Indentation for all lines in the block

Common Code Blocks:

  • if statements: if condition:
  • Functions: def function_name():
  • Loops: for item in list:
  • Classes: class ClassName:
# Code blocks with colons and indentation
temperature = 75

# Colon starts the block, indentation groups the code
if temperature > 70:
    print("It's warm outside!")
    print("Good weather for a walk")
    
    # Nested blocks need more indentation
    if temperature > 90:
        print("But it's quite hot!")
        print("Stay hydrated!")

print("Weather check complete")

📝 Lines and Statements

Python code is organized into lines, and each line typically contains one statement (instruction).

Line Structure Rules:

  • One statement per line (recommended for readability)
  • No semicolons needed (unlike some languages)
  • Long lines can be continued using backslash \ or parentheses
# Lines and statements
print("=== LINES AND STATEMENTS ===")

# One statement per line (recommended)
first_name = "John"
last_name = "Smith"
age = 30

# Line continuation for long statements
long_message = "This is a very long message that " + \
               "continues on the next line"

# Better way using parentheses
better_message = ("This is a long message "
                  "that spans multiple lines "
                  "in a cleaner way")

print(long_message)
print(better_message)

💬 Comments in Python

Comments are notes you add to explain your code. Python ignores comments when running your program, but they help humans understand what the code does.

Comment Types:

  • Single-line: Use # symbol
  • Multi-line: Use multiple # lines or triple quotes """
# This is a single-line comment
name = "Python"  # Comments can go at the end of lines too

# Multiple single-line comments
# can be used to explain
# more complex concepts

"""
This is a multi-line comment
using triple quotes. It can span
several lines and is useful for
longer explanations.
"""

# Calculate area of rectangle
length = 10  # in feet
width = 8    # in feet
area = length * width  # area calculation

print(f"Area: {area} square feet")

🎨 Whitespace and Formatting

Python cares about leading whitespace (indentation) but is flexible with other spacing. Good formatting makes your code easier to read.

Formatting Guidelines (PEP 8):

  • 4 spaces per indentation level
  • Spaces around operators: x = 5 + 3 (not x=5+3)
  • No trailing spaces at the end of lines
  • Two blank lines before functions and classes
  • One blank line between logical sections
# Good formatting examples
print("=== FORMATTING EXAMPLES ===")

# Proper spacing around operators
first_name = "Alice"
last_name = "Johnson"
full_name = first_name + " " + last_name

# Function with proper formatting
def calculate_total(price, tax_rate):
    tax = price * tax_rate
    total = price + tax
    return total

# Using the function
item_price = 29.99
tax_rate = 0.08
final_price = calculate_total(item_price, tax_rate)

print(f"Name: {full_name}")
print(f"Total: ${final_price:.2f}")

❌ Common Structure Mistakes

Understanding common mistakes helps you avoid them and write better Python code.

Frequent Errors:

  • IndentationError: Inconsistent or wrong indentation
  • Missing colons: Forgetting : after if, def, etc.
  • Mixed tabs/spaces: Using both in the same file
  • Wrong nesting: Indentation doesn't match logic
# Common mistakes and corrections
print("=== STRUCTURE EXAMPLES ===")

# CORRECT: Proper indentation and colon
age = 20
if age >= 18:  # Don't forget the colon!
    print("You're an adult")
    print("You can vote")

# CORRECT: Consistent indentation in functions
def greet_user(name):  # Colon required
    print(f"Hello, {name}!")  # 4 spaces indentation
    print("Welcome!")         # Same indentation

greet_user("Python Learner")

🐍 Python's Design Philosophy

Python's structure reflects its philosophy of beautiful, readable code. The language encourages practices that lead to clean, maintainable programs.

Core Principles:

  • "Readability counts" - Code should be easy to understand
  • "Beautiful is better than ugly" - Clean structure preferred
  • "Simple is better than complex" - Avoid unnecessary complexity
  • "There should be one obvious way to do it" - Consistent approaches
# Python philosophy in action
print("=== PYTHON PHILOSOPHY ===")

def process_grade(name, score):
    """Process a student's grade and give feedback"""
    
    # Clear, readable structure
    if score >= 90:
        grade = "A"
        message = "Excellent work!"
    elif score >= 80:
        grade = "B" 
        message = "Good job!"
    elif score >= 70:
        grade = "C"
        message = "Satisfactory"
    else:
        grade = "F"
        message = "Needs improvement"
    
    # Clear output
    print(f"Student: {name}")
    print(f"Score: {score}")
    print(f"Grade: {grade}")
    print(f"Feedback: {message}")

process_grade("Alice", 87)

🌟 Building Good Habits

Starting with good structure habits will help you throughout your programming journey. Clean code is easier to debug, maintain, and share.

Programming Best Practices:

  1. Configure your editor to show whitespace and use 4 spaces
  2. Practice with simple examples to build muscle memory
  3. Read error messages carefully—Python gives helpful structure error messages
  4. Be consistent in your formatting style

📋 Key Structure Rules Summary

RuleExampleWhy Important
Use indentationif True: followed by indented codeGroups code into blocks
Add colonsif age >= 18:Starts new code blocks
4 spaces standard print("Hello")Consistent, readable formatting
One statement per linename = "Alice"Easier to read and debug
Use # for comments# This explains the codeDocuments your code

🧠 Test Your Knowledge

Ready to test your understanding of Python code structure?

🚀 What's Next?

Excellent! You now understand how Python organizes code with indentation, colons, and proper structure. Next, we'll learn about adding helpful comments to document your code.

Continue to: Writing Comments

Keep up the great work! Your code is getting more professional! 📝

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent