Your first Python application#

Let start directly with the famous Hello World application in the Python interactive shell. The Python interactive shell can be used for very short applications like to run print("Hello World").

Starting interactive Python shell#
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.

File hello.py with Hello World#
1print("Hello World.")

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

Run the Python file hello.py#
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 like Linux 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.

File hello.py a the Hello World application#
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. Again we get Hello World. on the screen.

Run the Python file hello.py#
1$ chmod +x hello.py
2$ hello.py
3Hello World

But what does this all mean? Let start with the first line where tell Linux 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 chapter Packages and virtual environments we will go deeping into why this important when we start working with virtual environments.

Line 1 of file hello.py#
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.

Lines 3-4 of file hello.py#
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.

Lines 7-8 of file hello.py#
7if __name__ == "__main__":
8    main()

Note

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