The Python REPL is not something you try once and then forget. It is a read-eval-print loop, and it works like a workbench on your desk. There is no file to save and there is no program to restart, so you get an instant answer to the question "what does this actually do?". Working developers use it to look at unfamiliar libraries, to test an idea in three lines, and to check a suspicion without touching the code they are in the middle of. This lesson turns the prompt into a habit that you keep.
The previous lesson in this module covered "print(), input() and Your First Variables", and this lesson is the last one in the Python Setup and First Program module.
What is the Python REPL?
Start the interpreter with no script and you land at a prompt that ends in three chevrons. You type an expression, Python works out its value, and the value is printed back to you. Type a statement instead, and nothing is printed, because a statement has no value to show. That single difference explains most of what the prompt does.
# eval() works out an expression and gives back its value.
# exec() runs statements and gives back None.
print('eval ->', eval('2 ** 10'))
print('exec ->', exec('total = sum(range(11))'))
print('total is now', total)
The REPL uses exactly these two rules inside, which is why typing 2 ** 10 prints 1024 while typing x = 2 prints nothing at all. The last result also stays in a variable named _, so you can use it again without typing it once more. That saves a surprising amount of time when you are reading through a library.
Starting the prompt takes one command: python on Windows, and python3 on macOS and Linux. A few flags make it more useful. The command python -i your_script.py runs the script and then drops you into the prompt with all of the script's variables still in place, and that is the quickest way to check what a script really did. python -q hides the banner, and python -v prints every module as it loads, which shows you how much a single import pulls in.
How do you inspect things without leaving the prompt?
Three built-in functions do most of the inspecting. dir() lists what an object has, help() explains it, and type() tells you what it is. The inspect module gives you sharper versions of the same tools, and it also works inside a script, which makes it much more useful in real work.
import inspect
def greet(name, excited=False):
"""Return a greeting for name."""
suffix = '!' if excited else '.'
return 'Hello, ' + name + suffix
# Names that do not start with _ are the public ones.
public_names = []
for name in dir(greet):
if not name.startswith('_'):
public_names.append(name)
print('public names:', public_names)
print('name :', greet.__name__)
print('signature :', inspect.signature(greet))
print('docstring :', inspect.getdoc(greet))
print('source :')
print(inspect.getsource(greet))
Run that and you have seen a function's interface, its documentation, and its code without opening a single file. When you are about to use a library function that you have never used before, this is the fastest way to see what it accepts and whether it really does what its name suggests. The same dir() trick works on any object. Filtering out the names that start with an underscore leaves you with the public parts of a class or a module.
Two smaller habits are worth forming. help('module.name') pulls up the documentation for anything that you can import, and repr() shows the exact form of a value, which is how you spot a trailing space or a hidden character that is breaking your comparisons.
Why do multi-line blocks confuse people at the prompt?
The REPL decides whether your input is finished by looking at the syntax alone. When you type def greet(name):, it shows a continuation prompt of three dots and waits for more, because a function body is not complete yet. When you type a blank line, it runs the block.
That behaviour makes indentation problems harder to read at the prompt than they are in a file. One stray space turns a valid block into an IndentationError: unexpected indent that points at a line you cannot see, because the prompt has no line numbers. The practical rule is simple: use the REPL to explore values, and use a file to write functions.
import code
# InteractiveConsole is the machinery behind the real prompt.
console = code.InteractiveConsole(locals={'tax_rate': 0.2})
console.push('subtotal = 100')
console.push('total = subtotal * (1 + tax_rate)')
console.push('print(f"total = {total}")')
console.push('2 ** 10')
The last line prints 1024 with no print call, because the console works in "single" mode, where the result of an expression is shown just like it is at the ordinary prompt. You can also embed this machinery in your own program, and that is how debugging consoles and teaching tools are built.
How do you inspect a program's state right after it runs?
There are three techniques, and each one gives you more control than the one before it.
python -i script.pyruns the script and then opens the prompt with the script's variables still in place. You can look at values, call functions, and run pieces again without editing anything.exec(open('script.py').read())inside a running prompt runs a file again in the current session. It is useful when you have changed a value and you want the file to see it.code.interact(local=globals())drops a full prompt inside a running program and hands it the program's own variables. It is a two-line debugging aid, and you delete it afterwards.
There is also a permanent upgrade available. If you set the PYTHONSTARTUP environment variable to the path of a Python file, CPython runs that file every time you start an interactive session. Put your most-used imports in it, and every prompt starts with them already loaded.
import os
startup = os.environ.get('PYTHONSTARTUP')
print('PYTHONSTARTUP is set to:', startup or '(not set)')
if startup and os.path.exists(startup):
with open(startup, encoding='utf-8') as handle:
print('your startup file would run these lines:')
for line in handle.read().splitlines():
print(' ', line)
Your turn: build a twenty-minute REPL habit
- Start the prompt and type
2 ** 10, and then type_. Check that the value is still parked there. - Import a module that you use often. Run
dir()on one function andinspect.signature()on another. Write both signatures in a notes file, because you will look them up again and again. - Run
python -ion the tip calculator from the previous lesson, and inspect its variables at the prompt without changing the file. - Create
startup.pywith two imports that you always want. SetPYTHONSTARTUPto its full path, open a new prompt, and confirm that your imports are already there. - Finally, time yourself. For one whole day, use the prompt for every "what is the value of this expression" question. Most beginners find out that they were opening the editor just to check one expression, and that this round trip was costing them minutes every day.
The short version
- The REPL works out expressions and prints their values. Statements give no output, which is why assignment looks silent.
- Start it with
pythonorpython3, and keep it open after a script withpython -i script.py. dir(),help(),inspect.signature(), andrepr()answer most "what is this?" questions in seconds.- Write functions in files and not at the prompt, because the prompt has no line numbers for error messages.
- Set
PYTHONSTARTUPto a file of your favourite imports, so that every session starts ready to use.