COMPUTER PROGRAMMING 1 (PYTHON) • FUNCTIONS & MODULARITY

Organizing Multi-File Programs — I can organize a small multi-file program by importing functions from another file at my level.

Learn to split your Python code across multiple files using imports so your projects stay clean and reusable.

Historical Context & Motivation

In the earliest days of computing, programs were small enough to fit on a single page. Programmers would write every instruction in one continuous file, and things worked fine—for a while. As software grew more complex in the 1960s and 1970s, developers realized that cramming thousands of lines into one file made code almost impossible to read, debug, or share with teammates. The concept of modularity—breaking a program into separate, self-contained pieces—became one of the most important ideas in all of computer science.

Python, created by Guido van Rossum in 1991, was designed from the start to support modular programming. Its import system lets you pull functions, variables, and classes from one file into another with a single line of code. This system draws on decades of programming language evolution, from early Fortran subroutine libraries to the module systems of languages like Modula-2 and Ada.

1957
Fortran & Subroutine Libraries
Fortran introduced the concept of subroutines that could be compiled separately and linked together, planting the seed for multi-file programs.
1978
Modula-2 & Formal Modules
Niklaus Wirth designed Modula-2 with an explicit module system, separating interface from implementation and inspiring future languages.
1991
Python 0.9 Released
Guido van Rossum released Python with a built-in import system, making multi-file organization accessible even for beginners.
2000s
Package Managers & PyPI
The Python Package Index (PyPI) emerged, letting developers share entire libraries of modules that anyone could import with a simple install command.

Today, virtually every real-world Python application—from web servers to data science notebooks—is organized across multiple files. The question this lesson addresses is straightforward: How do you split your code into separate files and then bring the pieces back together using Python's import statement?

Core Principles of Multi-File Organization

Before you start splitting code into files, you need to understand a few foundational ideas. These principles explain why multi-file programs work, why they are useful, and how Python's import mechanism ties everything together.

1

Module

A module is simply a Python file (ending in .py) that contains functions, variables, or classes. Any .py file you create is already a module.
2

Import Statement

The import statement tells Python to load code from another module so you can use its functions and variables in your current file.
3

Namespace

A namespace is a container that holds the names defined in a module. It prevents name collisions—two modules can each have a function called calculate() without conflict.
4

Separation of Concerns

This design principle says each file should handle one specific responsibility—for example, one file for math helpers, another for user input, and a third to run the main program.
5

Reusability

When functions live in their own module, you can import them into multiple programs without copying and pasting. Write once, use many times.
✦ KEY TAKEAWAY
Think of a multi-file program like a kitchen with labeled drawers. Instead of dumping every utensil, spice, and gadget into one giant pile, you organize them into separate drawers (files). When you need the blender, you open the "appliances" drawer (import the module) and grab it. Everything is easier to find, and you can rearrange one drawer without messing up the rest.

Visual Explanation — How Imports Connect Files

The diagram below shows a small multi-file Python project. The main program file, main.py, imports functions from two helper modules: math_helpers.py and greeting.py. Notice how import arrows flow from the main file toward the modules it depends on. Each module contains its own functions, and main.py can use any function it imports.

The main program main.py imports specific functions from two helper modules. The dashed arrows show the direction of the import—main.py reaches into each module to grab only the functions it needs.

In the diagram, notice that math_helpers.py also contains a subtract() function, but main.py only imports add. This is one advantage of the from ... import ... syntax—you bring in only what you need, keeping your namespace clean and your code easy to follow.

How Python's Import System Works

When Python encounters an import statement, it follows a specific process behind the scenes. Understanding this process helps you avoid common errors and structure your projects correctly.

The Three Steps of Importing

  1. Step 1 — Locate the file. Python searches for the module in a set of directories, starting with the folder where your main script lives. If the module file is in the same folder, Python finds it immediately.
  2. Step 2 — Execute the file. Python runs the entire module file from top to bottom. All function definitions, variable assignments, and class definitions in that file become available.
  3. Step 3 — Bind names. Depending on which import syntax you used, Python either creates a reference to the whole module or places specific names directly into your current file's namespace.

Import Syntax Options

Python gives you several ways to import. The two most common for beginners are shown below. Each has a slightly different effect on how you call the imported function.

Common import syntax options in Python
SyntaxHow You Call the FunctionWhat Happens
import math_helpersmath_helpers.add(3, 5)The entire module is loaded. You access functions using dot notation (module_name.function_name).
from math_helpers import addadd(3, 5)Only the specified function is brought into your namespace. You call it directly by name.
from math_helpers import add, subtractadd(3, 5) or subtract(10, 4)Multiple specific functions are imported at once. Separate names with commas.
from math_helpers import *add(3, 5)All names from the module are imported. This is generally discouraged because it can cause name collisions.
⚠️ Important Rule
All files must be in the same folder (directory) for a simple import to work. If main.py and math_helpers.py are in different folders, Python won't find the module without additional configuration. For now, always keep your project files together.

Detailed Breakdown — Structuring Your Project

Knowing the syntax is only half the battle. You also need to decide which functions belong in which file. A well-organized project groups related functions together and keeps the main program file focused on running the show. The diagram below shows a slightly larger project that a high school student might build—a simple quiz game.

A quiz game project split into four files. The main script quiz.py imports from three helper modules, each responsible for a different concern: generating questions, scoring answers, and displaying output.

When deciding how to split your code, ask yourself: Does this group of functions share a single purpose? If yes, they belong in the same module. If a function does something clearly different—like displaying output versus calculating a score—it should go in a separate file. You don't need dozens of files for a small project; even splitting into just two files (a helper module and a main script) is a huge improvement over one massive file.

💡 Naming Tip
Name your module files using lowercase letters and underscores (snake_case). Avoid spaces, hyphens, or starting with a number. Good names: math_helpers.py, string_utils.py. Bad names: Math Helpers.py, 2helpers.py.

Worked Example — Building a Tip Calculator with Two Files

Let's walk through a complete example. You are building a simple tip calculator. You'll create a helper module called tip_helpers.py that contains the calculation function, and a main script called main.py that handles user interaction.

Tip Calculator — Two-File Setup
1
Step 1 — Create the helper module (tip_helpers.py)Create a new file called tip_helpers.py. Define a function called calculate_tip that takes two parameters: the bill amount and the tip percentage. The function returns the tip amount.
def calculate_tip(bill, tip_percent): return bill * (tip_percent / 100)
2
Step 2 — Add a second helper functionIn the same file, add a function called calculate_total that returns the bill plus the tip. This keeps all math logic in one module.
def calculate_total(bill, tip_percent): tip = calculate_tip(bill, tip_percent) return bill + tip
3
Step 3 — Create the main script (main.py)Create a second file called main.py in the same folder. At the top, import the two functions you need from tip_helpers. Notice that you write the module name without the .py extension.
from tip_helpers import calculate_tip, calculate_total
4
Step 4 — Write the user interaction codeBelow the import, add code that asks the user for input, calls the imported functions, and prints the results.
bill = float(input("Enter bill amount: $")) percent = float(input("Tip percentage: ")) tip = calculate_tip(bill, percent) total = calculate_total(bill, percent) print(f"Tip: ${tip:.2f}") print(f"Total: ${total:.2f}")
5
Step 5 — Run the programOpen a terminal in the project folder and run python main.py. Python finds tip_helpers.py in the same directory, loads the functions, and your program works. If the user enters a bill of $50 and a 20% tip, the output is:
Tip: $10.00 Total: $60.00
✦ WHY THIS MATTERS
Notice how main.py is short and readable—it only handles input and output. All the math lives in tip_helpers.py. If you later build a restaurant receipt printer, you can import the same calculate_tip function into that new project without rewriting anything.

Single-File vs. Multi-File — Strengths & Limitations

Not every program needs to be split across multiple files. For tiny scripts—say, 20 lines or fewer—a single file is perfectly fine. But as your projects grow, the advantages of multi-file organization become overwhelming. The table below compares the two approaches across several important dimensions.

Single-file vs. multi-file Python programs
DimensionSingle-File ApproachMulti-File Approach
ReadabilityGets harder to navigate as lines increase. Scrolling through hundreds of lines to find a function is frustrating.Each file is short and focused. You can quickly locate any function by opening the right module.
ReusabilityFunctions are trapped inside one file. To reuse them, you'd have to copy-paste.Any module can be imported into future projects with a single line.
CollaborationMultiple people editing the same file often leads to merge conflicts.Team members can each work on different modules simultaneously.
DebuggingAn error anywhere could be anywhere—you search the entire file.Error messages point to the specific module and line number, narrowing your search.
Setup ComplexityZero setup—just write code. Great for quick experiments.Requires planning: deciding which functions go where, naming modules, keeping files in one folder.
✦ WHEN TO SPLIT
A practical rule of thumb: once your file exceeds about 100 lines, or once you have two or more groups of functions that serve clearly different purposes, it's time to split. Think of it like organizing a school binder—when your notes from three subjects are all jumbled together, even 30 pages feel chaotic. Separate them into labeled tabs, and suddenly everything makes sense.

Connection to Advanced Concepts

The skills you're building now lay the groundwork for much more powerful Python features. As you advance, you'll encounter packages, third-party libraries, and object-oriented modules. Understanding how a basic import works makes all of these topics feel like natural extensions rather than entirely new ideas.

From beginner imports to professional Python practices
What You Learn NowWhat It Leads To
Importing functions from a file in the same folderPackages — folders of modules with an __init__.py file that Python treats as a single importable unit
Writing helper modules like math_helpers.pyThird-party libraries — modules published by other developers (e.g., import requests) that you install via pip
Using from module import func syntaxSelective imports & aliases — techniques like import numpy as np used throughout data science
Separating concerns across filesSoftware architecture — patterns like MVC (Model-View-Controller) used in professional web and app development

You may also encounter the if __name__ == "__main__": guard. This special block lets a module behave differently when it is run directly versus when it is imported by another file. Code placed inside that block only runs if the file is the entry point, not when it is imported. This is an important pattern you'll explore as you build larger programs.

Practice Problems

PROBLEM 1 — CONCEPTUAL
In your own words, explain the difference between import utils and from utils import greet. How does each affect the way you call the greet function?
PROBLEM 2 — BASIC CALCULATION
You have a file called conversions.py containing this function: def cm_to_inches(cm): return cm * 0.3937 Write the import statement you would place in main.py (same folder) and show how you would call the function to convert 25 cm to inches and print the result.
PROBLEM 3 — INTERMEDIATE
You are building a program with two modules. The file geometry.py contains: def area_rect(length, width): return length * width def perimeter_rect(length, width): return 2 * (length + width) In main.py, you write from geometry import area_rect. Can you now call perimeter_rect(5, 3) in main.py? Explain why or why not, and describe how to fix it if needed.
PROBLEM 4 — APPLIED
You are working on a group project: a simple grade book program. Your team has three people. Describe how you would split the code across at least three Python files. For each file, list its name and at least one function it would contain. Then show the import statements that main.py would need.
PROBLEM 5 — CRITICAL THINKING
Consider two modules, file_a.py and file_b.py. If file_a.py imports from file_b.py, and file_b.py also imports from file_a.py, what potential problem could arise? Suggest at least one strategy to avoid it.

Lesson Summary

In this lesson, you learned that a module is any Python file ending in .py, and you can bring its contents into another file using an import statement. The two primary syntaxes are import module_name (which requires dot notation) and from module_name import function_name (which lets you call the function directly). For simple projects, all files must be in the same folder.

Splitting your program across multiple files follows the principle of separation of concerns: each module handles one specific job. This makes your code more readable, more reusable, and easier to debug. As you advance, these same skills will prepare you for working with packages, third-party libraries, and professional software architecture patterns.

Varsity Tutors • Computer Programming 1 (Python) • Organizing Multi-File Programs