From 13fbc0941db96e5a602c90fe767417bfb71d9462 Mon Sep 17 00:00:00 2001 From: Jan Lerking Date: Sun, 22 Sep 2024 19:36:41 +0200 Subject: [PATCH] if __name__ lesson. /JL --- lesson_1/hello_world.py | 8 ++++++++ lesson_1/launching_python_file.py | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 lesson_1/hello_world.py create mode 100644 lesson_1/launching_python_file.py diff --git a/lesson_1/hello_world.py b/lesson_1/hello_world.py new file mode 100644 index 0000000..f2f45c1 --- /dev/null +++ b/lesson_1/hello_world.py @@ -0,0 +1,8 @@ +import os + +def main() -> None: + print("Hello world!") + print("From: ", os.getcwd()) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/lesson_1/launching_python_file.py b/lesson_1/launching_python_file.py new file mode 100644 index 0000000..457d664 --- /dev/null +++ b/lesson_1/launching_python_file.py @@ -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. \ No newline at end of file