One file, two lives
The file calc.py is written from the program itself, so you can see both lives. runpy.run_path(..., run_name="__main__") runs the file exactly like python calc.py would, so __name__ becomes __main__ and the guarded block runs.
Any .py file is a module you can import. The line if __name__ == "__main__": lets one file work both as a program and as a library, and sys.path is the list of folders Python searches, which is why a file named after a standard module can break your program.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a file temperature.py with a function to_fahrenheit(c) that turns degrees Celsius into Fahrenheit. Add a main guard that prints to_fahrenheit(100) only when the file is run directly. Then, from your program, import it and call to_fahrenheit(37).
Write a program that prints I am the main program when it is run directly, and I was imported when another file imports it. Use __name__ and an if/else.
Make a folder libs containing a module greeting.py with one function hello() that returns "hello". Add the folder libs to sys.path, import greeting, and print greeting.hello().
Explain it without notes
What does if __name__ == "__main__": do, and why do people use it?
How does Python decide which file to load for import foo?
Why can naming your file random.py break a program, and how do you diagnose it?
What is the difference between python calc.py and python -m calc?
Expected output
main program: my __name__ is __main__
calc: my __name__ is calc
imported, add(4, 5) = 9
--- now run calc.py like 'python calc.py' ---
calc: my __name__ is __main__
calc: run directly, self-test: 5