Installing Python and Writing Our First Program

Learning objectives

In this lesson, we will write our first program, called “Hello, World!” This program, which prints the message “Hello, World!” to the console, is the classic start to any programming course. This program may seem simple, but it represents a significant first step in our journey to learn how to program in Python.

To write our first program, we will need to learn how to download Python and install a text editor that will make coding in Python easy.

Note: Each chapter of Programming for Lovers comprises two parts. First, the “core text” presents critical concepts at a high level, avoiding language-specific details. The core text is followed by “code alongs,” where you will apply what you have learned while learning the specifics of the language syntax.

Code along summary

Setup

Before writing our first program, you will need to perform two installations:

  1. Download and install the Python programming language at https://www.python.org/downloads/. The website should automatically detect your operating system and provide you with the appropriate version for your computer. (If you are using Windows, make sure that you select the option to add Python to PATH during installation.)
  2. Download and install a text editor. We suggest the integrated development environment Visual Studio Code (VS Code), which can be downloaded from https://code.visualstudio.com.

Ensuring that your Python installation is working

Once you have installed Python and VS Code, we need to ensure that our installation is working and that we can run Python programs. To do so, we will check that Python has been installed to PATH, a list of folders that your computer searches through when you type a command in the terminal. That’s why installing Python “to PATH” is so important: it makes sure that when we run Python, your computer will run the version that you just installed.

To check your installation, open a command line terminal.

  • In Windows, search for cmd from your start screen. This should bring up the “Command Prompt” app as a suggestion. Click to open the app.
  • In macOS, open the Terminal app, which is contained in Applications > Utilities.

In the terminal, execute the following command to see the location of your Python installation by typing the following command and then pressing return.

On macOS/Linux, you should type the following:

where python3

On Windows, you should type the following:

where python

You should see a path to the Python program that you just installed. On Windows, you should see the following:

C:\Users\<YourUsername>\AppData\Local\Programs\Python\Python313\python.exe

On macOS, you should see the following:

/usr/local/bin/python3

What to do if you have another version of Python

If you have already installed Python using another installation (such as Anaconda, Miniconda, or another Python version), then executing the above command may show something else listed first. If not, then please skip this section. If so, then you need to update your PATH so that your new installation comes first. This is because when we execute a Python command, whichever installation is found first in the PATH will be the one that is run.

To prioritize the recent installation to occur first, follow these steps, depending on your operating system.

Windows:

  1. Open the Start menu, search for “Environment Variables”, and click Edit the system environment variables.
  2. Click Environment Variables… at the bottom.
  3. Under User variables, find the variable named Path, select it, and click Edit.
  4. Move the line that points to your new Python installation (something like C:\Users\<YourUsername>\AppData\Local\Programs\Python\Python313\) to the top, above any entries that mention Anaconda or Miniconda.
  5. Click OK and restart your terminal application.

macOS:

  1. Open your shell configuration file (~/.zshrc if you’re using the default zsh shell). To do so, execute the following command in Terminal.
nano ~/.zshrc
  1. This will bring up a text editor within the terminal, with a file. If there is content there, then add this line at the very end of the file:
export PATH="/usr/local/bin:$PATH"

This ensures that /usr/local/bin/python3 (your new installation) is found before any other installations.

  1. Save the file (Ctrl + O, Enter) and exit (Ctrl + X).
  2. Then, restart your terminal.

Now when you execute where python3 (macOS) or where python (Windows) in the terminal, you should see /usr/local/bin/python3 appear at the top of your installations, as desired.

Opening VS Code and establishing a code directory

Open VS Code. On the left side of the page, click “Open Folder”.

The window that opens on my computer defaults to my /Users/phillipcompeau home directory. Create a new folder called python.

Note: The screencaps provided below all use macOS, but the process is similar in Windows.

After creating the python directory, click “Open”, which will set your workspace to be the python folder.

On the left side of your VS Code window, you will see the python folder shortcut appear. Next to this folder, click the folder button to create a new subdirectory of python. Name the new folder that you created src. This is where we will place our source code for this course.

Finally, make a subfolder of src, and name it hello. Then, create a new file in the hello directory called main.py. This file, which will contain our “Hello, World!” program, is a plain text file, but the .py extension indicates that this file will contain code in the Python programming language.

Installing the Python extension for VS Code

We are nearly ready to write our program, but we need to perform one additional installation. Technically, this installation isn’t required to run Python code, but it will make working with Python even easier.

In VS Code, click the “extensions” tab on the left side of the screen, which looks like a square getting added to a block of three squares. (An extension is an add-on program that provides additional features.)

Then, in the extension search bar, type python. The top result should be an extension named Python. Beneath it, click the button that says Install. This extension will provide code highlighting in addition to some other features like code suggestions.

Writing our “Hello, World!” program

Close any pop-up messages from VS Code, and click the file icon on the left tab to bring up the file explorer.

You should see the main.py file that you created in your center window. We will type our program in this file.

We first will define the code that we intend to run, which we will place inside of the definition of a special function called main(). We will work with functions throughout this course, and so we will say much more about functions soon, but for now, just think of the main() function as the part of the code that we wish to run.

The first line of the function, def main():, defines the function name; note that the colon is necessary. The subsequent lines of the function must be indented, using either tabs or spaces, as long as we are consistent (in this course, we use four spaces). In this case, the function only contains a single additional line, with a command print("Hello, World!"). The print() command is built into Python, and it will print what is contained inside the parentheses. In this case, we provide print() with the message "Hello, World!", which should be enclosed in parentheses.

def main():
    print("Hello, World!")

Next, we need to tell Python to execute this function. We only want to execute this function if Python is running the code in the file. We will show below how to run this file, and when we do so, Python sets a special variable called __name__ equal to the value "__main__". If this is the case, then we want to run the code in main(). Accordingly, we add an if statement to our code to check if the code is being run, and if so, then we execute the main() function.

def main():
    print("Hello, World!")
    
if __name__ == "__main__":
    main()

We have now written our program! Before continuing, the most important thing that we need to do is save our code. A solid white circle at the top of main.py indicates that your code is not saved.

Save your code, which will remove the solid white circle.

Before continuing, we pause to note that even though our program is only four lines long, understanding how it works can be challenging to programming newcomers. If so, don’t worry! In subsequent code alongs, we will explain variables and functions in much greater detail. For now, you only need to keep in mind that the structure of our runnable program will always be as follows:

def main():
    # code that we wish to run
    
if __name__ == "__main__":
    main()

The last two lines of our program will always be the same, and we will place the code that we wish to run inside the indented block of def main().

Navigating using the command line

We will run our program in the command line terminal. Open a terminal window if you do not already have one open from our previous work with installing Python. When you look at the terminal, you will likely see your home directory appear at the left side of the window. For example, the current line in my terminal window shows phillipcompeau@Mac-mini-2. This indicates that the terminal considers its present working directory to be my home directory, /Users/phillipcompeau.

We already know that our code is contained within a python/src directory that lives inside of this home directory. So, how can we navigate there in the terminal application?

First, execute the following command. The cd command tells the terminal to “change directory” into the folder indicated after the command, which in this case is the python directory.

cd python

We know that we are currently within the Python directory because the start of the current line will show the home directory followed by python. On my computer, it shows phillipcompeau@Mac-mini-2 python.

The cd command allows us to navigate to a folder within the current directory, but it also allows us to return to the parent folder using the command cd ..; execute this command below, and you will return to the home directory.

cd ..

We now want to navigate into the directory that contains our program, which is python/src/hello. We could do this by executing three separate commands: cd python, then cd src, and then cd hello. However, we will instead execute a single cd command to take us directly to python/src/hello.

cd python/src/hello

You should now see the word hello appear in the command line next to your username to indicate that the navigation was successful. On my computer, the terminal shows phillipcompeau@Mac-mini-2 hello.

Before we run our program, we will point out two additional helpful terminal commands. The command pwd tells you the present working directory, which on my computer currently displays /Users/phillipcompeau/python/src/hello.

pwd

We also can execute a command to indicate the contents of the present working directory. On macOS, the command is ls.

ls

On Windows, the equivalent command is dir.

dir

Running our program

Let’s execute a command to run the code that we have written. Assuming that you followed the steps in the previous section to navigate into python/src/hello, execute the following command in the terminal on macOS or Linux to run the code in main.py. Here, the python3 keyword indicates that we are performing a task with Python 3; when this keyword is followed by a file name in the present working directory, Python will run the code in that file.

python3 main.py

If you’re on a Windows machine, you should use the python command instead of python3.

python main.py

Regardless of what operating system we are using, we obtain the same result: the message Hello, World! printed to the console.

You may be curious what happens behind the scenes when we type python3 main.py. A special program called the Python interpreter is called into action; its job is to read your file and carry out those instructions line by line. First, it processes the definition of the main() function. Second, it encounters if name == "main": , which is true, and so it enters the if statement and executes main().

You might like to think of your code as a recipe, and the interpreter as the cook that follows the recipe to make the dish. This is why checking that Python is installed and on your PATH was so important earlier: it ensures that when you type python3 in a terminal command, your computer knows where to find the interpreter.

Note: The reason why we use the python3 command instead of python on macOS is to distinguish it from Python 2, which was automatically installed on older Apple machines.

Shortcut: running a program within VS Code

At the bottom of the VS Code window, you will notice a tab named Terminal. Click on this tab, which will show a command-line interface. Because we set our VS Code home directory to the python directory inside our home folder, the VS Code terminal will default to having this directory as the present working directory.

As a result, we can repeat the above steps to run our program within VS Code. First, navigate into the appropriate subfolder.

cd src/hello

Then, run your code by executing python3 main.py (macOS/Linux) or python main.py (Windows). You will once again see Hello, World! printed to the console, this time from within the comfort of VS Code.

You did it!

Congratulations on building your first program! This is one of the hardest things to do in programming, and it’s all downhill from here. You are now ready to start learning the basics of Python in the next lesson. Happy coding!

And if you would like to run this program in the browser, check out our sandbox below. We’ll be providing sandbox links throughout our coding challenges.

Click Run 👇 to try it!

Page Contents
Scroll to Top