The Python interactive console (also called the Python interpreter or Python shell) provides programmers with a quick way to execute commands and try out or test code without creating a file.
Providing access to all of Python’s built-in functions and any installed modules, command history, and auto-completion, the interactive console offers the opportunity to explore Python and the ability to paste code into programming files when you are ready.
This tutorial will go over how to work with the Python interactive console and leverage it as a programming tool.
You should have Python 3 installed and a programming environment set up on your computer or server. If you don’t have a programming environment set up, you can refer to the installation and setup guides for a local programming environment or for a programming environment on your server appropriate for your operating system (Ubuntu, CentOS, Debian, etc.)
The Python interactive console can be accessed from any local computer or server with Python installed.
The command you will use to enter into the Python interactive console for your default version of Python is:
- python3
If you’re using a local virtual Python environment, you will enter in the default version of Python with:
- python
If you set up a programming environment according to the prerequisites section, you can launch and access the version of Python and modules you have installed in that environment by first entering into it with the following command:
- cd environments
- . my_env/bin/activate
Then typing the python
command:
- python
In this case, the default version of Python is Python 3.8.10, which is displayed in the output once we enter the command, along with the relevant copyright notice and some commands you can type for extra information:
OutputPython 3.8.10 (default, Jun 2 2021, 10:49:15)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
The primary prompt for the next command is three greater-than signs (>>>
):
-
You can target specific versions of Python by appending the version number to your command, with no spaces:
Note: As of January 2020, Python 2 has been sunset and improvements will no longer be made. To learn more, refer to [Sunsetting Python 2] (https://www.python.org/doc/sunset-python-2/)
- python2.7
OutputPython 2.7.18 (default, Mar 8 2021, 13:02:45)
[GCC 9.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Here, we received the output that Python 2.7.18 will be used. If this is our default version of Python 2, we could also have entered into this interactive console with the command python2
.
Alternatively, we can call the default Python 3 version with the following command:
- python3
OutputPython 3.8.10 (default, Jun 2 2021, 10:49:15)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
We could have also called the above interactive console with the command python3.8
.
With the Python interactive console running, we can move onto working with the shell environment for Python.
The Python interactive interpreter accepts Python syntax, which you place following the >>>
prefix.
We can, for example, assign values to variables:
- birth_year = 1868
Once we have assigned the integer value of 1868
to the variable birth_year
, we will press return and receive a new line with the three greater-than signs as a prefix:
- birth_year = 1868
-
We can continue to assign variables and then perform math with operators to get calculations returned:
>>> birth_year = 1868
>>> death_year = 1921
>>> age_at_death = death_year - birth_year
>>> print(age_at_death)
53
>>>
As we would with a script in a file, we assigned variables, subtracted one variable from the other, and asked the console to print the variable that represents the difference.
Just like in any form of Python, you can also use the interactive console as a calculator:
>>> 203 / 20
10.15
>>>
Here, we divided the integer 203
by 20
and were returned the quotient of 10.15
.
When we are writing Python code that will cover multiple lines, the interpreter will use the secondary prompt for continuation lines, three dots (...
).
To break out of these continuation lines, you will need to press ENTER
twice.
We can see what this looks like in the following code that assigns two variables and then uses a conditional statement to determine what to print out to the console:
>>> sammy = 'Sammy'
>>> shark = 'Shark'
>>> if len(sammy) > len(shark):
... print('Sammy codes in Java.')
... else:
... print('Sammy codes in Python.')
...
Sammy codes in Python.
>>>
In this case the lengths of the two strings are equal, so the else
statement prints.
Note that you will need to keep Python indenting convention of four whitespaces, otherwise you will receive an error:
>>> if len(sammy) > len(shark):
... print('Sammy codes in Java.')
File "<stdin>", line 2
print('Sammy codes in Java.')
^
IndentationError: expected an indented block
>>>
You can not only experiment with code across multiple lines in the Python console, you can also import modules.
The Python interpreter provides a quick way for you to check to see if modules are available in a specific programming environment. You can do this by using the import
statement:
>>> import matplotlib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'matplotlib'
In the case above, the module matplotlib was not available within the current programming environment.
In order to install it, we’ll need to leave the interactive interpreter and install with pip as usual:
- pip install matplotlib
OutputCollecting matplotlib
Downloading matplotlib-3.4.3-cp38-cp38-manylinux1_x86_64.whl (10.3 MB)
...
Installing collected packages: numpy, python-dateutil, kiwisolver, pillow, pyparsing, cycler, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.3.1 matplotlib-3.4.3 numpy-1.21.2 pillow-8.3.1 pyparsing-2.4.7 python-dateutil-2.8.2
Once the matplotlib module along with its dependencies are successfully installed, you can go back into the interactive interpreter:
- python
- import matplotlib
-
At this point you will receive no error message and can use the installed module either within the shell or within a file.
There are two main ways to leave the Python interactive console, either with a keyboard shortcut or a Python function.
The keyboard shortcut CTRL
+ D
in *nix-based systems or CTRL
+ Z
then the CTRL
key in Windows systems will interrupt your console and return you to your original terminal environment:
...
>>> age_at_death = death_year - birth_year
>>> print(age_at_death)
53
>>>
sammy@ubuntu:~/environments$
Alternatively, the Python function quit()
will quit out of the interactive console and also bring you back to the original terminal environment that you were previously in:
>>> octopus = 'Ollie'
>>> quit()
sammy@PythonUbuntu:~/environments$
When you use the function quit()
, it will show up in your history file, but the keyboard shortcut CTRL
+ D
will not be recorded:
...
age_at_death = death_year - birth_year
print(age_at_death)
octopus = 'Ollie'
quit()
Quitting the Python interpreter can be done either way, depending on what makes sense for your workflow and your history needs.
One of the useful things about the Python interactive console is that all of your commands are logged to the .python_history
file in *nix-based systems, which you can look at in a text editor like nano, for instance:
- nano ~/.python_history
Once opened with a text editor, your Python history file will look something like this, with your own Python command history:
import pygame
quit()
if 10 > 5:
print("hello, world")
else:
print("nope")
sammy = 'Sammy'
shark = 'Shark'
...
Once you are done with your file, you can press CTRL
+ X
to leave nano.
By keeping track of all of your Python history, you can go back to previous commands and experiments, and copy and paste or modify that code for use in Python programming files or in a Jupyter Notebook.
The Python interactive console provides a space to experiment with Python code. You can use it as a tool for testing, working out logic, and more.
For use with debugging Python programming files, you can use the Python code
module to open up an interactive interpreter within a file, which you can read about in our guide How To Debug Python with an Interactive Console.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Python is a flexible and versatile programming language that can be leveraged for many use cases, with strengths in scripting, automation, data analysis, machine learning, and back-end development. It is a great tool for both new learners and experienced developers alike.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!