Learn Without Walls
← Previous Lesson Lesson 4 of 4 Practice Problems →

Lesson 10.4: Organizing Your Code

What you will learn:

1. Creating Your Own Modules

Any Python file can be used as a module. If you save functions in a .py file, you can import and use them in other files. This is one of the most powerful ways to organize your code.

Step 1: Create a module file (helpers.py)

# helpers.py - a custom module with useful functions

def greet(name):
    """Return a greeting message."""
    return f"Hello, {name}! Welcome!"

def calculate_average(numbers):
    """Calculate the average of a list of numbers."""
    if len(numbers) == 0:
        return 0
    return sum(numbers) / len(numbers)

def is_even(number):
    """Check if a number is even."""
    return number % 2 == 0

Step 2: Use the module in another file (main.py)

# main.py - uses functions from helpers.py
import helpers

# Use functions from the helpers module
message = helpers.greet("Alice")
print(message)

scores = [85, 92, 78, 95, 88]
avg = helpers.calculate_average(scores)
print(f"Average score: {avg}")

print(helpers.is_even(7))  # False
print(helpers.is_even(4))  # True
Hello, Alice! Welcome!
Average score: 87.6
False
True
Key rule: Both files must be in the same folder for the import to work. The module file name (without .py) becomes the name you use in the import statement.

2. Understanding __name__ == "__main__"

You will often see this pattern in Python files. It controls what code runs when a file is executed directly versus when it is imported as a module.

__name__: A special variable that Python sets automatically. When a file is run directly, __name__ is set to "__main__". When a file is imported as a module, __name__ is set to the module's name.

Example: math_tools.py

# math_tools.py

def double(n):
    return n * 2

def triple(n):
    return n * 3

# This code ONLY runs when math_tools.py is run directly
# It does NOT run when math_tools is imported
if __name__ == "__main__":
    print("Testing math_tools...")
    print(double(5))   # 10
    print(triple(5))  # 15
    print("All tests passed!")

When Run Directly vs. Imported

# Running directly: python math_tools.py
# Output:
# Testing math_tools...
# 10
# 15
# All tests passed!

# Importing in another file:
import math_tools
# No output! The test code doesn't run.

# But the functions are available:
print(math_tools.double(8))  # 16
16

This pattern is incredibly useful because it lets you:

3. Project Structure

As your programs grow, organizing code into multiple files becomes essential. Here is a typical project structure:

my_project/ main.py # Entry point - runs the program helpers.py # Utility functions data_processing.py # Data-related functions requirements.txt # Package dependencies README.md # Project description

A Mini Project Example

# data_processing.py
def clean_name(name):
    """Remove extra spaces and capitalize properly."""
    return name.strip().title()

def validate_age(age):
    """Check if age is a valid positive number."""
    return isinstance(age, int) and age > 0

def format_record(name, age):
    """Create a formatted string for a person's record."""
    return f"{clean_name(name)} (age {age})"
# main.py
from data_processing import clean_name, validate_age, format_record

# Process a list of people
people = [
    ("  alice  ", 30),
    ("BOB", 25),
    ("  charlie johnson  ", 35)
]

for name, age in people:
    if validate_age(age):
        print(format_record(name, age))
Alice (age 30)
Bob (age 25)
Charlie Johnson (age 35)

4. Best Practices

Follow these guidelines to keep your code organized and maintainable:

Do: Group Related Functions Together

# string_utils.py - all string-related helpers
def reverse_string(text):
    return text[::-1]

def count_vowels(text):
    return sum(1 for c in text.lower() if c in "aeiou")

def is_palindrome(text):
    clean = text.lower().replace(" ", "")
    return clean == clean[::-1]

Check Your Understanding

You have a file called utils.py with a function format_name(). How would you import and call that function in another file?

You have two main options:

Option 1: import utils then call utils.format_name("alice")

Option 2: from utils import format_name then call format_name("alice")

Both files must be in the same directory for the import to work.

Key Takeaways

← Previous Lesson Lesson 4 of 4 Practice Problems →