Sub topic 7
Trying code in the interactive interpreter
This chapter assumes you have already installed Python 3 and confirmed with python3 --version (or py --version on Windows) that the interpreter runs from your terminal. You should also be able to open a terminal and type commands. Everything here uses only the standard interpreter, with no extra packages.
What the REPL is
The interactive interpreter is usually called the REPL, short for Read-Eval-Print Loop. It repeats four steps:
- Read a line (or block) of code that you type.
- Evaluate it, meaning run it.
- Print the result.
- Loop back and wait for the next input.
The REPL keeps state between inputs. A variable you assign on one line is still there on the next. This makes it a good place to test a small idea, check how a built-in behaves, or explore data before you put the code in a file.
Starting and leaving the REPL
Start the REPL by running the interpreter with no file name.
python3
# On Windows, use: pyPython prints its version and a build line, then shows the primary prompt >>>. Here is a short session.
>>> 2 + 3
5
>>> name = "Ada"
>>> print("Hello, " + name)
Hello, Ada
>>> exit()To leave, you have these options:
| Method | Works on | Notes |
|---|---|---|
| `exit()` or `quit()` | All systems | Works everywhere. Prefer the parentheses form. |
| `Ctrl+D` | macOS, Linux | Sends end-of-file on an empty line. |
| `Ctrl+Z`, then `Enter` | Windows | Sends end-of-file on Windows consoles. |
In recent Python versions, typing exit without parentheses also works. Older versions print a hint telling you to call it. Using exit() avoids the difference.
Expressions and the automatic echo
When you enter an expression, the REPL prints its value without you calling print. When you enter a statement such as an assignment, there is no value, so nothing is echoed.
>>> 10 / 4
2.5
>>> 10 // 4
2
>>> x = 10 // 4
>>> x
2
>>> "py" * 3
'pypypy'Notice that the string result is shown with quotes: 'pypypy'. The REPL echoes the repr() of the value, which is a representation meant for programmers. print shows the str() form, which is meant for display. The difference matters when you debug.
>>> text = "line one\nline two"
>>> text
'line one\nline two'
>>> print(text)
line one
line twoThe echo has one more rule. If an expression evaluates to None, the REPL prints nothing. Many functions, including print itself, return None.
>>> None
>>> result = print("hi")
hi
>>> result
>>> result is None
TrueThe underscore variable
In the REPL, the name _ holds the value of the last echoed expression. This is handy for chaining a quick calculation.
>>> 1920 * 1080
2073600
>>> _ / 1_000_000
2.0736_ is set only by the REPL. It does not work this way in scripts. Do not assign to _ yourself in a session, because that hides the feature until you delete the name with del _.
Multi-line input and the secondary prompt
When a statement needs more lines, such as a for loop, a function, or an if block, the REPL shows the secondary prompt .... Indent the body, and finish the block by pressing Enter on an empty line.
>>> for n in range(3):
... print(n, n * n)
...
0 0
1 1
2 4
>>> def square(n):
... return n * n
...
>>> square(7)
49Common mistakes with multi-line input:
- Forgetting the blank line. The block does not run until you press
Enteron an empty...line. - Wrong indentation. An unindented body gives an
IndentationError. - Pasting code with blank lines inside a block. In older REPLs, a blank line ends the block early and the rest produces errors. Newer versions handle pasted blocks better, but a script file is more reliable for anything longer than a few lines.
>>> if True:
... print("oops")
File "<stdin>", line 2
print("oops")
^
IndentationError: expected an indented block after 'if' statement on line 1Errors do not end the session
An error in the REPL prints a traceback and returns you to the prompt. Your earlier variables remain.
>>> total = 5
>>> total + missing
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'missing' is not defined
>>> total
5The file name in the traceback is <stdin>, because the code came from standard input and not from a file. Chapter 11 covers how to read tracebacks in detail. For now, the last line tells you the error type and message.
This persistence has a downside. After many edits you may forget what is defined, and a function may depend on a variable you created by hand. If the session gets confusing, exit and start a new one. A fresh REPL is cheap.
Built-in help and inspection
The REPL is also a documentation browser. Three built-ins do most of the work.
>>> type(3.5)
<class 'float'>
>>> dir("abc")[-3:]
['title', 'translate', 'upper']
>>> help(str.upper)
Help on method_descriptor:
upper(self, /)
Return a copy of the string converted to uppercase.type(x)shows the type of a value.dir(x)lists the names (attributes and methods) available on an object. The list is long, so slicing it is useful.help(x)shows the documentation. It opens in a pager. Pressqto leave the pager and return to the prompt.
You can also call help() with no argument to enter an interactive help mode, and type quit to leave it.
Importing modules in the REPL
You can import standard-library modules and try them immediately.
>>> import math
>>> math.sqrt(144)
12.0
>>> from pathlib import Path
>>> Path.cwd()
PosixPath('/home/ada/projects')On Windows, the last line shows a WindowsPath with a Windows-style path. The current directory also matters for imports. If you start the REPL in a folder that contains a file named math.py, import math may load your file instead of the standard module. This is a common cause of confusing errors. Avoid naming your files after standard modules.
If you edit a module after importing it, the REPL does not reload it automatically. Exit and restart, or use importlib.reload.
>>> import importlib
>>> import mymodule
>>> importlib.reload(mymodule)Useful editing shortcuts
The REPL offers some line editing without any setup.
- Up and Down arrows move through your input history.
- Left and Right arrows move within the current line.
- Tab inserts indentation in the basic REPL. On many Linux and macOS builds with
readline, Tab completes names. Recent Python versions (3.13 and later) ship a newer REPL with colour, multi-line editing, and a history browser opened withF2.
Which features you get depends on your Python version and platform. If your session looks different from the examples, check your version first.
Running a single command without opening the REPL
The -c option runs a string of code and exits. It is useful for quick checks in shell scripts.
python3 -c "import sys; print(sys.version)"
# On Windows, use: py -c "import sys; print(sys.version)"The -i option does the opposite combination. It runs a file, then drops you into the REPL with the file's names still defined. This is a good way to inspect the results of a script.
python3 -i hello.pyWhen to use the REPL and when to use a file
| Use the REPL for | Use a script file for |
|---|---|
| Testing one expression or a short idea | Anything you want to run again |
| Checking what a function returns | Programs longer than a few lines |
| Exploring an unfamiliar object with `dir` and `help` | Code you want to keep in version control |
| Quick arithmetic | Code that takes command-line arguments |
The REPL does not save your work. When you exit, the variables and functions are gone. The next chapters move your code into a file so you can run it repeatedly.
Summary of key points
- The REPL reads, evaluates, prints, and loops, and it keeps variables between inputs.
- Expressions echo their
repr(). Statements andNoneresults echo nothing. _holds the last echoed value, but only in the REPL.- A
...prompt means Python expects more of the block. An empty line ends it. - Errors print a traceback and leave the session usable.
- Use
type,dir, andhelpto explore. - Exit with
exit(),Ctrl+D(macOS, Linux), orCtrl+ZthenEnter(Windows).
Exercise
In a fresh REPL you type a = 6, then a * 7, then _ + 1. What does the REPL print for each line, and why does the first line print nothing?
Show answer
The first line prints nothing because an assignment is a statement and has no value to echo. The second line prints 42, which is the value of the expression. That value is stored in _, so the third line prints 43.
Exercise
You type print("hi") in the REPL and then _. Does _ hold 'hi'? Explain what you see.
Show answer
No. print writes text to the screen and returns None. The REPL does not echo None, so it does not update _. Typing _ shows whatever the last echoed value was, or raises a NameError if nothing has been echoed yet in this session.
Exercise
You start the REPL in a folder that contains a file named random.py you wrote earlier, and import random behaves strangely. What is the likely cause and the fix?
Show answer
Python searches the current directory first, so it imported your random.py instead of the standard-library random module. Rename or move your file (and delete any __pycache__ copy of it), then start a new REPL session.