Every .py file can be used in two ways: run directly as a program, or imported as a module. The difference lies in how it is used, not in how it is written, and Python tells the file which way it is being used.
Two roles of a .py file
Script
Module
Purpose
A program that performs a task when run
A library of definitions for other files
How it is used
python report.py in a terminal, or Run in an IDE
import report from another file
Value of __name__
"__main__"
The module’s name, e.g. "report"
Typical contents
Statements that do the work, input and output
Functions, classes and constants
When you run a script from a terminal, the path is relative to the current folder: run python report.py in the folder that contains it, or give its path, as in python projects/report.py. python -m module_name runs a module found on sys.path as a script.
The main guard
Python sets the variable __name__ in every module. Code placed under the main guard runs only when the file is executed directly:
The main guard
if __name__ == "__main__": statements that run only when the file is executed as a script
Key takeaways
The same .py file can be a script (run) or a module (imported).
__name__ is "__main__" when run, the module name when imported.
Put script-only code under if __name__ == "__main__":.
Run scripts with python file.py, or python -m module for a module on the path.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain what happens, step by step, when use_temperature.py imports temperature.py from the example above.
Show worked answer
Python finds temperature.py on sys.path, compiles it and runs its top-level code once with __name__ set to "temperature". The def creates the function c_to_f, and the top-level print shows “temperature.py loaded, name = temperature”. The test __name__ == "__main__" is false, so the demonstration block is skipped. Control returns to use_temperature.py, which calls temperature.c_to_f(25) and prints 77.0.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/modules-and-packages/modules-versus-scripts/ to read this page.