if __name__ lesson. /JL

This commit is contained in:
2024-09-22 19:36:41 +02:00
parent 077478c126
commit 13fbc0941d
2 changed files with 33 additions and 0 deletions

8
lesson_1/hello_world.py Normal file
View File

@@ -0,0 +1,8 @@
import os
def main() -> None:
print("Hello world!")
print("From: ", os.getcwd())
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,25 @@
"""
How to launch a python script, the right way
"""
# This is a very short introduction into the correct way of launching a python script.
# There's only 1 correct way of doing this, shown below.
import os
def main() -> None:
print("Hello world!")
if __name__ == "__main__":
main()
# In short a python script can be devided in 3 parts.
# Imports, definitions, directly executable.
# Only your main file should contain these 3 parts/sections. Any imported file should only contain the first 2
# parts. This prevents you from running a file that's only supposed to be imported, directly from terminal.
# Your main file must follow this setup. Failing to do so, will give you issues further down the path.
# The overall purpose of this setup is that the file you execute with python, is called "__main__" and
# any other files is called by their import name.
# Any code definitions are not executed until you actually call the function/method.