Register to get access to free programming courses with interactive exercises

Working with the REPL Python: Setting up the environment

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:

asciicast

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:

asciicast

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:

asciicast

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
  • Lines without >>> are the result of the code you entered

If you decide to try it yourself, don't enter the invitation. Instead, enter the code that follows the >>> characters.

Canonical representation and printout

In the examples above, you can see that when you type, the string appears in the interpreter's output with quotation marks and special characters. Numbers are output as numbers. The same approach applies to any other values.

Most values are output as a canonical string representation. We can copy the values presented in this way to the prompt line and execute them again. The canonical representation is usually considered correct code in Python.

You can get a canonical representation of any value using the repr function. Let's see how it works:

>>> repr(42)
'42'
>>> repr("foo")
'"foo"'
>>> repr(None)
'None'

Note that the result of the print function call doesn't contain quotation marks or special characters. It is because we can see printing a string.

REPL and None

You should also know how REPL maps the return from the function to None.

The correct answer is that it doesn't. We did it on purpose. If the function doesn't return a result explicitly, it returns None. And to avoid cluttering up the REPL logs with infinite Nones, the interpreter's authors decided to suppress the output of this value.

It is why, in the REPL example above, we didn't see that the print function returned None.

But we can still see None in the REPL if needed. To do this, you have to wrap the print call in another print call:

>>> print(42)
42
>>> print(print(42))
42
None

Now we see this value because the second print receives None as the input and the results and prints the line already.

In your work, you may encounter a situation where a function in the REPL is called but doesn't return anything. There's nothing wrong with that. Maybe, your function returns None.

Entering multi-line code

You can also enter multi-line code in the Python REPL. You can't edit lines you've already entered. But it's convenient to enter small functions in this way.

Imagine you enter a line that isn't complete in terms of meaning. In this case, REPL changes the prompt to ... and waits for a new line in addition to the one already entered. This way, we can enter a whole function definition along with docstring and logic.

The end of all multi-line code is an empty line, so you can't use it in your code.

Examples with multi-line code would look like this:

>>> def is_positive(x):
...     """Return True if the argument is positive"""
...     if x <= 0:
...          return False
...     return True
...
>>> is_positive(42)
True

Connecting modules in the REPL

You may need functions from modules built into Python. To use them, you need to import the necessary module or function:

>>> import operator
>>> from math import sqrt
>>> operator.pow(2, 5)
32
>>> sqrt(64)
8.0

The REPL is a handy calculator

The Python REPL is easy to use as a regular calculator. The only difference is that REPL doesn't remember results between calculations. To fix this, we can use a variable to store intermediate results:

>>> result = 42 * 7
>>> result = result - 1
>>> result = result // 2
>>> result
146

Note that the assignment doesn't output any values. Built-in statements never return values. It is one reason why they can't be part of expressions.

Using variables helps if we need intermediate results later. But if you need the result only in the following expression, you can use the variable _.

It stores the result of the previous command:

>>> 42 * 7
294
>>> _ - 1
293
>>> _ // 2
146
>>> _
146

Now it's more like a calculator you're used to. Intermediate results are saved and displayed after each action.

Moreover, the _ variable stores the last successfully obtained result. If an error occurs during the execution of a line of code, the previous result won't be lost. Also, the result won't be lost if you enter statements.

It helps if you want to store the current value in a variable. Here's an example demonstrating error tolerance and preservation of results during execution:

>>> 42
42
>>> _ // 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> _ // 6
7
>>> a = _
>>> _ + 20
27
>>> a
7

The _ variable is only available in the REPL. We cannot declare this variable in the code, but it'll work like any other variable. Keep this in mind when transferring code from the REPL to modules.


Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs
profession
new
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.