Python includes a built-in REPL — an interactive Python interpreter. It is a program that runs as a shell and executes code in Python.
The acronym REPL stands for:
- Read — read input from the user
- Eval — execute the entered code
- Print — print the result on the screen
- Loop — enter standby mode again
To start the REPL, we type python3
. You can then execute the Python code and see the result. REPL displays the operation result directly on the screen and enters command entry standby mode again.
This way of working is good for debugging, simple computations, and quick tests of hypotheses along the lines of "How does this thing work?"
Let's look at an example of working with the REPL:
To exit the REPL, we press Ctrl + D.
Built-in documentation
Python allows you to add documentation to the code. It supports this feature at the syntax level. The essential documentation tool is documentation strings or docstrings.
The documented function looks like this:
def add(x, y):
"""Add one argument to another"""
return x + y
We generate online documentation from such strings. And this documentation is also available for viewing directly in the REPL. To view the documentation, use the help
function.
Let's declare the add
function in REPL, try to call it, and then look at the definition of our function:
The help
function also works in interactive mode, which we can do using the help()
command without arguments. In this case, you will see the welcome page, and the prompt on the input line will change to help>
. The prompt page shows which command you can enter. To exit the help mode, quit
or press Ctrl+D.
The topics
command is helpful for beginners. It displays a list of articles you can read in the REPL help mode.
We'll enter help mode and display a list of topics. Then we'll open an article that talks about Python operators:
REPL and code examples in sources
REPL is so widespread that you can find examples depicting a piece of dialog between a programmer and REPL in many sources. It looks something like this:
>>> 1 + 2
3
>>> len("Thomas")
6
>>> "Hello" + '\n' + "World!"
'Hello\nWorld!'
>>> print("Hello" + '\n' + "World!")
Hello
World!
Notice how the lines begin differently:
- Lines with
>>>
have code entered by the programmer. The>>>
symbol itself is called an invitation