Executing Python#

A program is a file on your computer that can be executed. Executing (or running) a program means making it do what it is designed to do. Programs can do many things, like perform calculations, process data, play music, display images, download content from the internet, or execute other programs. For programs that are designed to keep running, we also say to start or open a program. In this course, we only write simple programs that print text and numbers.

To create a program, programmers write instructions in a programming language they’ve learned. These instructions are called the source code of the program, and writing code is also called coding. The source code can be written and read by humans, but computers cannot understand it directly. To be executed, the source code must be translated into a language that the computer understands.

For Python programs, this translation is done using a program called the Python interpreter. When we talk about installing Python we mean installing this interpreter on the computer.

There are different ways to execute Python code. Some are more appropriate when the program is finished, while others are more appropriate when still writing and testing the program. In this course, you learn how to write small Python programs and execute them to check whether they work as expected. Most of the time, you’ll execute your programs in the same way, but it’s useful to know there are multiple options.

With this text we introduce a few ways to execute Python code. The examples will use simple Python commands and you may guess what they do. Don’t worry if some parts seem unclear. As you gain experience with writing programs, you will also be able to understand program execution. During the course, we’ll revisit this topic. Some details of executing Python might vary depending on your operating systems and your Python installation. Here we explain the process in general terms, and the exercises provide specific instructions for Windows and macOS.

Terminal#

One way to execute Python code on any computer with Python installed, is from the terminal. The terminal, sometimes called the command line, lets you interact with your computer by typing commands as text. While you are probably more familiar with using a mouse to navigate, the terminal is widely used, providing access to advanced features. Using the terminal requires caution, as you can accidentally delete or modify important files or settings.

You can learn Python without the terminal, but it is useful to know, as it is always available regardless of other tools.

When you start a terminal, it displays some brief information. The last line ends with a symbol, called the prompt, indicating that the terminal is ready for input. The prompt is usually > on Windows and $ on MacOS. To run a command in the terminal, you need type it after the prompt and press Enter when done. We say that you enter the command.

To start a program from the terminal, type its name, optionally followed by any required arguments, and press Enter. To start the Python interpreter, you enter python.

You can only execute programs that your computer can find in the current folder, or in a special list of folders where the computer looks for programs to execute. This list is updated when you install new programs. For the python command to work, Python must be installed, and your computer must know its location. It is possible to have multiple versions of Python interpreter stored on your computer. Then you can specify which one to use. For example, if you want to execute Python version 3 interpreter you should enter python3 and if you want to execute the interpreter stored in the folder root/bin, you should enter root/bin/python.

Interactive mode#

When you start Python interpreter from the terminal, the Python interpreter will run in the same window as the terminal. To indicate that something has changed, the prompt will change to >>>, indicating that Python code is expected. Every Python command you enter is executed immediately, and you can enter the next one. If you enter the command which computes or prints something, it appears immediately in the next line. The text printed as a result of a command is called the output of the command. If you define something, it will be remembered as long as the session lasts. To end the session, you enter exit().

This way of executing Python code is called interactive execution.

When we want to show you some Python code executed interactively, we will make it look as in the box below. Here, >>> is the prompt of the Python interpreter, followed by the commands entered. The lines without >>> are the outputs of the previous command.

>>> print("Hello, world!")
Hello, world!
>>> a = 13
>>> print(a + 7)
20

The code block above looks like a dialogue between you and the computer: you enter commands, and the computer responds with output. Learning to program involves understanding why commands produce specific outputs and knowing which commands to use to get the desired output.

Script mode#

A downside of interactive execution is that the commands you entered are lost when you exit the session. If you want to run the same code again interactively, you must retype it.

Instead of starting from scratch every time, you can save the Python code it in a file. Then, you can make Python interpreter execute all commands from the file. For this, you need to tell the Python interpreter which file it should execute. This is done by adding the file name after the command python in the CLI.

For example, if your Python interpreter is located at root/bin/python3, and your Python code is in a file saved as root/Documents/my_program.py, you can run this file with the following command in CLI.

root/bin/python root/Documents/my_program.py

Most computers know where to find the Python interpreter so you can just write python. Furthermore, if you open CLI in the folder where the file is located, only need to write file name. Therefore, if you are in correct folder you only need to enter the following command.

python my_program.py

This way of executing Python code is called script execution, and the file containing the code is called a script.

When the python script is executed, the Python interpreter reads the commands from the file and executes them one by one. Any output is printed in the CLI. Each time a script is executed you start a new session, and definitions are kept for the duration of the script. Every time you run a script, you start fresh.

In this course, we will often write some Python code to be executed in a script mode, or the output of some code, or both. It will look as shown below.

print("Hello, world!")
a = 13
print(a + 7)
Hello, world!
20

While less interactive, this also resembles a communication: you write a list of commands and the computer responds with the output to all commands.

Output in the interactive and script mode#

There are small differences in how the output is presented depending on whether the Python code is executed interactively or as a script. The key difference is that in the interactive mode, you can ask the Python interpreter to evaluate (compute) something, and it will display the result even if you don’t ask it to print. In the script mode, you always need to ask the program to print, otherwise, it will not display anything. In a way, the interactive mode assumes that you want to see the result, while the script mode assumes that you want the program to move on.

Look at the example below to see how the output of the same commands look when executed in the script and interactive mode.

Interactive mode:

>>> print(7 + 13)
20
>>> 2 + 5
7
>>> b = 4 + 3
>>> print(b)
7

Script mode:

print(7 + 13)
2 + 5
b = 4 + 3
print(b)
20
7

In the interactive mode, the result of computation 2 + 5 is printed, while in the script mode it is not. Note that executing b = 4 + 3 never prints anything, because the result of this evaluation (the number 7) is used. We will cover details about this in the weeks to come.

Integrated development environments#

Integrated Development Environments (IDEs) are programs designed to help with writing executing and testing the code. IDEs are not needed to write Python code, but they can be extremely helpful. One simple IDE is the IDLE which comes with Python. You can start IDLE from CLI.

When you start IDLE, it opens a new window with the >>>, allowing you to execute Python code interactively, just like in the CLI. If you prefer to write a script, IDLE lets you open a blank page, write code, and save it as a Python script. You can then run the script by selecting the menu option, instead of typing a command.

Another popular IDE is VS Code, which requires additional installation. VS Code is a very powerful and highly customizable IDE. It can be used for many programming languages, not just Python. It has numerous features and allows extensions fo new features. Because of its complexity, it might be overwhelming for beginners.

Cell execution#

Both interactive and script mode have pros and cons. Script mode requires saving files, and if you want to experiment with the code, you might end up having many files with small changes. Interactive mode allows you to experiment, but only with one line of code at a time.

To get the best of both worlds, many IDEs (including VS Code, but not IDLE) allow Python scripts to be divided into smaller blocks, called cells. This is done by inserting #%% between the code blocks. Each cell can be executed independently, and the definitions are kept between cell executions. This lets you test parts of the code separately and re-run cells in any order and multiple times. However, you need to remember what has been executed and what has not. Such script can still be executed using the script mode, making it a very flexible way of writing and testing code.

For running cells, the IDE starts an interactive session, collect the code from the cell, and sends it to the Python interpreter. The output of the cell is collected and displayed in the IDE. This means that cell execution is built on top of interactive execution. The program providing this functionality is called a kernel, and needs to be installed separately from Python. When using a cell execution, starting a new session is done by restarting the kernel.

Output of the cell interaction is also a combination of interactive and script mode: the evaluation of the last command in the cell is printed, while the output of all other commands is not printed.

Jupyter notebooks#

A very popular way of running Python code is by incorporating it in Jupyter Notebook, a document which contains both text cells and code cells which can be executed. Jupyter Notebooks are saved in a file with the extension .ipynb.

The programs needed to view and run Jupyter Notebooks can be installed on your computer, and there are many popular online services that offer hosting Jupyter Notebooks for free. Executing Jupyter notebook requires a kernel, similar to the cell execution.

A big advantage of Jupyter Notebook is that you can include nicely-formatted text, images, videos, and mathematical formula in the same document with the code. This is very useful when preparing reports, tutorials, or teaching material for science classes. In many of the courses at DTU you will be given Jupyter Notebooks developed by the teachers, and you may be asked to modify or write Jupyter Notebooks for your assignments.

A disadvantage of Jupyter Notebook is that it can be hard to keep track of cell execution, similar to the cell mode. You need to consider the order in which the cells are executed, and how to break the code into cells. Furthermore, with Jupyter Notebooks, you might spend a lot of effort editing the notebook, because the code is in separated cells. Moving between cells, and different types of cells, can require a lot of editing expertise.

Python online#

Many online services allow running Python code in the browser. This can be useful when you don’t have Python installed on your computer, For example, when just starting the corse, or when working on a borrowed computer. We provide the online Run Python page, where you can try out Python code, without installing anything.

Executing Python when following this course#

The focus of this course is on writing and running python code, regardless of how it is executed.

However, for all assignments and the final exam you need to write a Python file (.py file) with your solution, which we test by running it. This requires only the Python interpreter, and relies fully on the definitions within the script. You can test your solution on your computer before submitting it, in the same way as we will test it after the submission.

To prepare for this, you should practice writing and executing Python script. You can successfully complete the course using only script execution, so this is the most important execution mode to learn.

While demonstrating the desired output, we may may display it as if the instructions were executed interactively. This is because interactive mode immediately shows the result of each command, making it easier to follow. You should therefore be familiar with how interactive mode looks, but you don’t have to execute the code interactively.

For development, cell execution can be helpful, but it requires that you know how cell execution works. If you decide to use cell execution, we recommend using cells within a .py file rather than Jupyter Notebooks. This approach allows you to test entire scripts easily and minimizes the time spent editing.

See the image below for a comparison of different ways to execute Python code on your computer.

image