3. Your first Python application
Let start directly with the famous
Hello World application in the Python shell. The Python shell can be used for very short applications like to run
$ python Python 3.9.1 (default, Jan 12 2021, 16:56:42) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello World.") Hello World. >>>
Python can also use file as the source to run the
Hello World application and if we create a file
hello.py with the content below we can execute it later.
Python can now use the file
hello.py as a source and it nicely prints
Hello World. to the screen.
$ python hello.py Hello World.
Now that we have a quick and dirty way of running
Hello World. we can take it to the next level and turn it a proper Python program you can execute on every Unix-like system with Python 3 installed. If we replace the content of
hello.py with the example below then we can run it it again and should still give
#!/usr/bin/env python3 def main(): print("Hello World.") if __name__ == "__main__": main()
If we also add the execute bit to the file
hello.py we can directly start it without prefexing it the Python interpreter. And again we get
Hello World. on the screen.
$ chmod +x hello.py $ hello.py Hello World
But what does this all mean? Let start with the first line where tell unix via a shebang to look the
python3 interpreter via the
env command. This guarantees that we always find the Python interpreter while we don’t set any hardcoded paths. In the PIP section we will go deeping into why this important when we start working with virtual environments.
Secondly we define a function called
main and we put the print statement for
Hello World. in this function. One thing that is different from other languages is that indentation is important and gives context to the statement.
def main(): print("Hello World.")
The third section is that we call the function called
main if we execute the file
hello.py. The exact reason for why we do this is explained in the modules section.
if __name__ == "__main__": main()
Most examples will be based on this example and the
mainfunction will be modified.