Skip to main content

How To Code in Python 3: How To Work with the Python Interactive Console

How To Code in Python 3
How To Work with the Python Interactive Console
    • Notifications
    • Privacy
  • Project HomeHow To Code in Python 3
  • Projects
  • Learn more about Manifold

Notes

Show the following:

  • Annotations
  • Resources
Search within:

Adjust appearance:

  • font
    Font style
  • color scheme
  • Margins
table of contents
  1. Introduction
  2. Python 2 vs Python 3: Practical Considerations
  3. How To Install Python 3 and Set Up a Local Programming Environment on Ubuntu 16.04
  4. How To Install Python 3 and Set Up a Local Programming Environment on macOS
  5. How To Install Python 3 and Set Up a Local Programming Environment on Windows 10
  6. How To Install Python 3 and Set Up a Local Programming Environment on CentOS 7
  7. How To Install Python 3 and Set Up a Programming Environment on an Ubuntu 16.04 Server
  8. How To Write Your First Python 3 Program
  9. How To Work with the Python Interactive Console
  10. How To Write Comments
  11. Understanding Data Types
  12. An Introduction to Working with Strings
  13. How To Format Text
  14. An Introduction to String Functions
  15. How To Index and Slice Strings
  16. How To Convert Data Types
  17. How To Use Variables
  18. How To Use String Formatters
  19. How To Do Math with Operators
  20. Built-in Python 3 Functions for Working with Numbers
  21. Understanding Boolean Logic
  22. Understanding Lists
  23. How To Use List Methods
  24. Understanding List Comprehensions
  25. Understanding Tuples
  26. Understanding Dictionaries
  27. How To Import Modules
  28. How To Write Modules
  29. How To Write Conditional Statements
  30. How To Construct While Loops
  31. How To Construct For Loops
  32. How To Use Break, Continue, and Pass Statements when Working with Loops
  33. How To Define Functions
  34. How To Use *args and **kwargs
  35. How To Construct Classes and Define Objects
  36. Understanding Class and Instance Variables
  37. Understanding Inheritance
  38. How To Apply Polymorphism to Classes
  39. How To Use the Python Debugger
  40. How To Debug Python with an Interactive Console
  41. How To Use Logging
  42. How To Port Python 2 Code to Python 3

How To Work with the Python Interactive Console

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.

Entering the Interactive Console

The Python interactive console can be accessed from any local computer or server with Python installed.

The command you generally will want to use to enter into the Python interactive console for your default version of Python is:

python

If you have set up a programming environment, you can launch the environment and access the version of Python and modules you have installed in that environment by first entering into that environment:

cd environments
. my_env/bin/activate

Then typing the python command:

(my_env) sammy@ubuntu:~/environments$ python

In this case, the default version of Python is Python 3.5.2, 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:

Output
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] 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:

python2.7
Output
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Here, we received the output that Python 2.7.12 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
Output
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

We could have also called the above interactive console with the command python3.5.

With the Python interactive console running, we can move onto working with the shell environment for Python.

Working with the Python Interactive Console

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.

Multiple Lines

When we are writing Python code the 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.

Importing 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:

(my_env) sammy@ubuntu:~/environments$ pip install matplotlib
Output
Collecting matplotlib
  Downloading matplotlib-2.0.2-cp35-cp35m-manylinux1_x86_64.whl (14.6MB)
...
Installing collected packages: pyparsing, cycler, python-dateutil, numpy, pytz, matplotlib
Successfully installed cycler-0.10.0 matplotlib-2.0.2 numpy-1.13.0 pyparsing-2.2.0 python-dateutil-2.6.0 pytz-2017.2

Once the matplotlib module along with its dependencies are successfully installed, you can go back into the interactive interpreter:

(my_env) sammy@ubuntu:~/environments$ 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.

Leaving the Python Interactive Console

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:

File: /home/sammy/.python_history
...
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.

Accessing History

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:

File: /home/sammy/.python_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.

Conclusion

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.

Annotate

Next Chapter
How To Write Comments
PreviousNext
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
Powered by Manifold Scholarship. Learn more at
Opens in new tab or windowmanifoldapp.org