Modules vs. Scripts
in Python
Understand the difference between running a Python file and importing it, and how __name__ == '__main__' lets you control both.
What Is a Script?
A script is a Python file you run directly from the command line or your editor. When you type python hello.py, Python reads the file top to bottom and executes every statement it finds.
What Is a Module?
A module is a Python file whose functions, classes, or variables are imported by another file. Instead of running it directly, you bring pieces of it into your own code with the import keyword.
Same File, Two Roles
Here is the key insight: every .py file can act as both a script and a module. The difference is how you launch it, not what is inside it.
The __name__ Variable
Every Python file automatically gets a special variable called __name__. Python sets its value before your code runs, depending on how the file was started:
The if __name__ Guard
By checking __name__, you can write code that only runs when the file is executed directly and is skipped when imported. This is called the main guard:
Script vs. Module at a Glance
| Script Mode | Module Mode | |
|---|---|---|
| How you start it | python file.py | import file |
| __name__ value | '__main__' | 'file' |
| Top-level code runs? | Yes | Yes |
| Guarded block runs? | Yes | No |
| Typical purpose | Entry point / demo | Reusable library |
Why This Matters
How to Apply the Pattern
Example 1: Simple Guard
Example 2: Without the Guard
Example 3: Two Files Working Together
Execution Flow
What Happens on Import?
Common Mistakes
Summary Cheat Sheet
| Concept | Key Detail |
|---|---|
| Script | A .py file run directly: python file.py |
| Module | A .py file imported by another: import file |
| __name__ | Auto-set to '__main__' (direct) or 'filename' (import) |
| Main Guard | if __name__ == "__main__": protects script-only code |
| Top-level code | Runs in both modes: keep it to defs and imports |
| sys.modules | Cache: a module's code runs only on first import |
Question 1 of 5
What is the value of __name__ when you run a file with python app.py?
Question 2 of 5
If utils.py contains a bare print("Loading") at the top level (no guard), what happens when another file runs import utils?
Question 3 of 5
File: stats.py
def mean(nums):
return sum(nums) / len(nums)
data = [10, 20, 30]
print("Mean:", mean(data))
A teammate imports stats in their own script. What problem will they encounter?
Question 4 of 5
Which of the following is the correct way to write the main guard in Python?
Question 5 of 5
When you import a module for the second time in the same Python session, what happens?