Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
CHAPTER GUIDE · GETTING STARTED

Scripts and magic commands

On this pageRun a saved scriptWhat makes a command “magic”?Keep the three places distinct

A script is a saved file of Python instructions, such as hello.py. An interactive session instead accepts instructions one at a time and keeps their results available for exploration. IPython adds convenience commands to this interactive style of working.

These conveniences are optional. Ordinary Python files remain the main way to save programs that can be run again.

Run a saved script

In a terminal opened in the folder containing hello.py, the standard command is:

python hello.py
Listing 45 — Run a saved script with the active Python.

This starts the program and displays its output. The file must exist in that folder, or the command must include its path.

To explore the same file interactively, activate the intended conda environment and start IPython by entering ipython in the terminal. If that environment does not contain IPython, install it there with conda install ipython first.

At IPython’s In [ ]: prompt, enter:

%run hello.py
Listing 46 — Run a saved file from an IPython session.

The script executes, and its names remain available for inspection in that session. This is useful when a program calculates values that you want to examine after it finishes.

What makes a command “magic”?

A magic command is an IPython instruction for working with the interactive session. A leading % marks a line command. These commands also work in Jupyter notebooks using the IPython Python kernel; they are not ordinary Python syntax and should not be copied into a .py file.1

Command Purpose
%pwd Show the session’s current working folder.
%run hello.py Execute a saved Python file from the session.
%timeit 2 + 2 Repeatedly measure the execution time of an expression.
Table 1 — A few useful IPython line magics.

%pwd helps explain a file-not-found error: it shows where the session is looking. %timeit is useful when comparing ways of performing a calculation. Its timing varies between computers and runs, so it is a measurement rather than a fixed program result.

Keep the three places distinct

  • Terminal: enter commands such as python hello.py, conda install numpy or ipython.
  • Python file or ordinary >>> prompt: enter Python statements such as print("Hello World!").
  • IPython prompt or a notebook cell using its Python kernel: enter Python statements and supported magic commands such as %run hello.py.

The distinction prevents a common source of confusion: a valid instruction entered in the wrong place. Exit a terminal IPython session with exit() when finished. With the tools prepared, the language chapters can concentrate on what the programs mean.


  1. IPython, Built-in magic commands. Syntax and kernel-specific behaviour checked on 22 October 2026.↩︎