
Code
Who Is Running Me?
Every module has a built-in variable called __name__:
- When you run a file directly (
python compass.py), its__name__is"__main__". - When it is imported (
import compass), its__name__is the module name,"compass".
That lets one file be both a reusable module and a runnable script. Put the "demo" code under a guard:
def heading(degrees):
...
if __name__ == "__main__":
print("compass demo:", heading(95)) # only when run directly
Without the guard, everyone who imports your module would see the demo print, which is noisy and sometimes slow!
runpy.run_path("compass.py", run_name="__main__") runs a file as if
you typed python compass.py. We use it below to test both ways.
Assignment
- In the
compass.pytext, move the demoprintunder anif __name__ == "__main__":guard, soimport compassis quiet. - At the very end of the main program,
print(__name__)to see what your program is called.
- In the
compass.pytext, move the demoprintunder anif __name__ == "__main__":guard, soimport compassis quiet. - At the very end of the main program,
print(__name__)to see what your program is called.
main.py Python sleeping
Press Run to try your code, then Check to test it.