Skip to content

Running code

There are two ways to run Python: type it line by line in the REPL, or save it in a file and run the file. This page shows both. It then explains the folder layout and the code blocks of this course.

All commands assume that your terminal is in my-course and that the environment is active (see Virtual environments).

The REPL (Read–Eval–Print Loop) is an interactive Python session. It reads one line of code, evaluates (runs) it, prints the result and waits for the next line. Use it to try small ideas fast.

Start it by typing python in the terminal:

Terminal
python

Python prints its version and then the prompt >>>. The prompt means “type your code here”. A line that starts with ... continues the code of the line above, for example the body of a loop. In this course, a REPL session looks like this:

>>> 21.5 * 9 / 5 + 32
70.7
>>> city = "Chicago"
>>> city.upper()
'CHICAGO'
>>> for reading in [19.5, 21.0]:
... print(reading + 0.5)
...
20.0
21.5

You type the code after >>> and .... Python prints the other lines. Two facts to notice:

  • The REPL shows the value of an expression on its own, without print(). That is why city.upper() displays 'CHICAGO'.
  • After a block such as a for loop, press Enter on an empty ... line to run it.

To leave the REPL, type exit() and press Enter. You can also press Ctrl + D on macOS and Linux, or Ctrl + Z then Enter on Windows. Everything you typed is gone when the session ends.

A script is a text file with Python code, saved with the ending .py. You run the whole file with one command. Scripts are how real projects run, and they keep your work.

  1. In VS Code, create the file hello.py in my-course with this code:

    hello.py
    readings = [21.5, 22.1, 20.8]
    average = sum(readings) / len(readings)
    print("Readings:", len(readings))
    print(f"Average: {average:.1f} °C")
    Output
    Readings: 3
    Average: 21.5 °C
  2. Run it in the terminal:

    Terminal
    python hello.py

The terminal shows the two lines from the Output block. You can also click the Run Python File button in VS Code, as on the editor page.

A script does not show the value of a bare expression. A line such as average on its own does nothing visible in a script. Always use print() to see a value. The course follows this rule in every code block.

REPL Script
Start python python name.py
Shows values yes, automatically only with print()
Keeps your code no yes, in the file
Best for quick tests lessons, exercises, projects

Keep all your course work in one project folder. After the next page, it looks like this:

my-course/
my-course/
├── .venv/ the environment (do not edit)
├── .vscode/
│ └── settings.json editor settings
├── data/ the course datasets
│ ├── sales.csv
│ ├── customers.csv
│ └── ...
├── output/ files your scripts write
├── requirements.txt the pinned library list
├── hello.py
└── m01_basics.py your scripts, one or more per module

Name your scripts after the module, for example m24_pandas.py or m24_exercises.py. Write any files your code creates into output/ or the project folder, never into data/, so the course data stays unchanged.

Course code reads data with paths such as data/sales.csv. That is a relative path: Python looks for it inside the working directory, the folder that your terminal is in when you run the script. So always run scripts from my-course. Then data/sales.csv points to my-course/data/sales.csv.

pathlib.Path represents a file path. Its method exists() checks whether the file is there:

from pathlib import Path
print(Path("data/sales.csv").exists())
Output
True

If this prints False, either the data is missing (see Get the data) or the terminal is in another folder. Type cd and the path to my-course to go back.

Every code block on this site has been run. Its output is real.

A Python block is usually followed by a block titled Output. The Output block shows exactly what the code prints:

total_revenue = 3596523.83
print(f"Total revenue: {total_revenue:,.2f}")
Output
Total revenue: 3,596,523.83

Run the code and compare your output with the Output block. If they differ, check your code, your Python version and your library versions. A block that prints nothing has no Output block.

Each block has a copy button in its top-right corner. It appears when you point at the block. It copies the code without the line numbers. Typing code yourself is good practice for short blocks. For long blocks, copy them, then read every line.

On a lesson page, the blocks build on each other. A later block uses the variables of earlier blocks. Put them into one script in the order of the page, and run the script after each new block. If you skip a block, a later block can fail with NameError, because a variable does not exist yet.

On exercise pages, each exercise stands alone. Run the page’s Setup block first (if it has one), then the exercise.

Some blocks are display-only. Examples are starter code for exercises, network code that needs the internet, and code that shows a pattern rather than a full program. These blocks never have an Output block. In starter code, comments mark the places where you write your own code:

Starter
celsius = 21.5
# TODO: convert to Fahrenheit and print the result

Blocks titled Terminal are commands for the terminal, not Python. A block that shows a whole file, such as requirements.txt or .vscode/settings.json, has the file name as its title.

Some lessons show an error on purpose, to teach you to read it. The Output block then shows the last line of the error message:

reading = int("n/a")
Output
ValueError: invalid literal for int() with base 10: 'n/a'

When you run such a block, Python prints a longer message called a traceback first. The last line names the error and is the same as in the Output block. Module 06 teaches you to read tracebacks.

Code that draws a chart ends with plt.show(). On your computer, it opens the chart in a window; close the window to let the script continue. On this site, the chart appears as an image directly below the code.

Download the datasets that the examples use: Get the data.