Chapter 4 Hello, World!

4.1 Learning objectives

  • Understand how to run Python scripts from the command line

4.2 Python “Hello, World!” example

  • Create a new file named 01-helloworld.py using the text editor and write the following code:

    #!/usr/bin/env python3
    print("Hello, World!")
    • The beginning of the first line, #!, it is called a “hashbang” or “shebang”. That indicates which interpreted should process (Python in this case) the file.

    • We use /usr/bin/env to find the Python interpreter in the user’s environment, which is more flexible than specifying a path like /usr/bin/python3. This way, it works regardless of where Python is installed on the system.

    • python3 is the interpreter that will run the script. It ensures that the script is executed with Python 3, which is important because Python 2 and Python 3 have different syntax and features.

    • Lastly print("Hello, World!") is the actual Python code that prints “Hello, World!” to the terminal.

4.3 Run a Python script

  • Save the file and make it executable:

    chmod +x 01-helloworld.py
  • In the terminal, run the script by typing:

    ./01-helloworld.py
  • You should see the output:

    Hello, World!

4.4 Summary

Congratulations! You have just:

  • Created a Python script that prints “Hello, World!” to the terminal

  • Made the script executable

  • Ran the script from the command line