Your first Python application

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 print(“Hello World”).

1$ python
2Python 3.9.1 (default, Jan 12 2021, 16:56:42)
3[GCC 8.3.0] on linux
4Type "help", "copyright", "credits" or "license" for more information.
5>>> print("Hello World.")
6Hello World.
7>>>

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.

1print("Hello World.")

Python can now use the file hello.py as a source and it nicely prints Hello World. to the screen.

1$ python hello.py
2Hello 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 Hello World.

1#!/usr/bin/env python3
2
3def main():
4    print("Hello World.")
5
6
7if __name__ == "__main__":
8    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.

1$ chmod +x hello.py
2$ hello.py
3Hello 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 Packages and virtual environments chapter we will go deeping into why this important when we start working with virtual environments.

1#!/usr/bin/env python3

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.

3def main():
4    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 chapter.

7if __name__ == "__main__":
8    main()

Note

Most examples will be based on this example and the main function will be modified.