python · level 3 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
marks your program's front door.
Every Python file is a module, and every module has a variable called __name__. Run the file directly and __name__ is "__main__". Import it from another file and __name__ is the module's own name, like "prices".
So code under if __name__ == "__main__": runs only when the file is the program itself. Other files can import its functions to reuse or test them, without the program starting up.
Professionals put the work in a main() function and call it from that block. That one call is the : the single, obvious place where the program starts.
def add_vat(pence):
return round(pence * 1.2)
def main():
for price in [999, 2450]:
print(f"{price} -> {add_vat(price)}")
if __name__ == "__main__":
main()
print("__name__ is", __name__) In Gwecode your code is always the file being run, so __name__ is always "__main__" here.
guess first
Follow the front door. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def main():
print("tool started")
print("loading")
if __name__ == "__main__":
main()
print("done")
your turn
Your turn. Give a tool its front door.
Type a name in the first blank. Then finish the if line with the value __name__ has when run directly, and call main in the last blank.
fix it
The report never appears. Fix it!
- Nothing appears, so
mainnever ran. Is the condition on line 4 ever true? - When a file is run directly,
__name__holds"__main__", with two underscores on each side. - Change "main" to "__main__" on line 4, then run.
nailed it
your programs have a proper front door. :D
__name__is"__main__"only when the file is run directly.- Put the work in
main()and call it from that block. - Imported files then share functions without starting up.
new words in your collection
- __name__
- entry point
This lesson isn’t saved. A free account remembers every lesson you finish.