The Python REPL is not a toy you try once on day one. It is a read-eval-print loop that behaves like a workbench: no file to save, no program to restart, an instant answer to "what does this thing actually do?". Professionals use it to inspect unfamiliar libraries, test a hypothesis in three lines, and check a suspicion without disturbing the code they are working on. This lesson turns the prompt into a habit you keep.
What is the Python REPL?
Start the interpreter with no script attached and you land at a prompt ending in three chevrons. You type an expression, Python evaluates it, and the value is printed back to you. Type a statement, and nothing is echoed because a statement has no value to show. That single difference explains most of what the prompt does.
# eval() evaluates an expression and hands back its value.
# exec() runs statements and hands back None.
print('eval ->', eval('2 ** 10'))
print('exec ->', exec('total = sum(range(11))'))
print('total is now', total)
The REPL uses exactly that pair of rules internally, which is why typing 2 ** 10 prints 1024 while typing x = 2 prints nothing. The last result is also parked in a variable named _, so you can refer to it without retyping it, which saves an astonishing amount of effort when you are exploring a library.
Launching it takes one command: python on Windows, python3 on macOS and Linux. A few flags make it more useful. python -i your_script.py runs the script and then drops you into the prompt with all of the script's variables still in scope, which is the fastest way to inspect what a script actually did. python -q suppresses the banner, and python -v prints every module as it is imported, which is a spectacular way to see how much a single import pulls in.
How do you inspect things without leaving the prompt?
Three built-ins 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 works from a script as well as at the prompt, which makes it far more useful in practice.
import inspect
def greet(name, excited=False):
"""Return a greeting for name."""
suffix = '!' if excited else '.'
return f'Hello, {name}{suffix}'
public_names = [n for n in dir(greet) if not n.startswith('_')]
print('name :', greet.__name__)
print('qualname :', greet.__qualname__)
print('signature :', inspect.signature(greet))
print('docstring :', inspect.getdoc(greet))
print('source :')
print(inspect.getsource(greet))
Run that and you have just seen a function's interface, its documentation, and its implementation without opening a single file. When you are about to use an unfamiliar library function, this is the fastest way to find out what it accepts and whether it does what its name suggests. The equivalent dir() trick works on any object: filtering out names that begin with an underscore leaves you with the public surface of a class or module.
Two smaller prompt habits are worth forming. help('module.name') pulls the documentation page for anything importable, and repr() shows you the unambiguous 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 from the syntax alone. When you type def greet(name): it prints a continuation prompt of three dots and waits for more, because a function body is not complete. When you type a blank line, it compiles and runs the block.
That behaviour means indentation problems at the prompt are much harder to read than in a file. A stray space turns a legal block into an IndentationError: unexpected indent that names 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 compiles in "single" mode, where expression results are echoed exactly as they are at the ordinary prompt. The same machinery can be embedded in your own program, which is how debugging consoles and teaching tools are built.
How do you inspect a program's state right after it runs?
Three techniques, in increasing order of control.
python -i script.pyruns the script and then opens the prompt with the script's globals intact. You can inspect variables, call functions, and re-run pieces without editing anything.exec(open('script.py').read())inside a running prompt re-executes a file in the current namespace, which is handy when you have changed a value you want the file to see.code.interact(local=globals())drops a full prompt into a running program, handing the program its own namespace. It is a two-line debugging aid that you can delete afterwards.
There is also a permanent upgrade available. If you set the PYTHONSTARTUP environment variable to the path of a Python file, CPython executes that file every time you start an interactive session. Put your most-used imports in it, and every prompt begins 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:
source = handle.read()
print('your startup file would run these lines:')
for line in source.splitlines():
print(' ', line)
Your turn: build a twenty-minute REPL habit
- Start the prompt and immediately type
2 ** 10, then_. Confirm the value is still parked there. - Import a module you use often and run
dir()on one function, theninspect.signature()on another. Write down the two signatures in a notes file; you will look them up constantly. - Run
python -ion the tip calculator you wrote in the previous lesson, then inspect its variables at the prompt without changing the file. - Create
startup.pycontaining two imports you always want, setPYTHONSTARTUPto its full path, open a new prompt, and confirm your imports are already there. - Finally, time yourself: use the prompt for every "what is the value of this expression" question for one day. Most beginners discover that they were opening the editor to evaluate a single expression, and that the round trip was costing them minutes a day.
The short version
- The REPL evaluates expressions and prints their values; statements produce 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, not at the prompt; the prompt has no line numbers for error messages.
- Set
PYTHONSTARTUPto a file of your favourite imports so every session starts warm.