When you’re executing Python code, the standard Python shell that comes with your Python installation is a natural tool to use. However, as you progress in your coding journey, you might find yourself seeking more powerful functionalities than the standard REPL offers. Luckily, IPython offers an enhanced version of interactive Python that can supercharge your capabilities.
Using the IPython shell is a fast way of learning Python and executing code without the need for a full-fledged integrated development environment (IDE), such as PyCharm. IPython adds great features to the Python experience with its magic commands, which the standard Python shell lacks. These can help you complete tasks more quickly.
In this tutorial, you’ll:
- Learn the major aspects and functionality of the IPython shell
- Write and execute code in IPython
- Integrate IPython in your Python scripts
- Use IPython’s magic commands in your coding sessions
- Learn how to save your sessions persistently in a Python file
To get started with IPython, you don’t need to be far along in your Python journey. In fact, IPython is an excellent learning tool because it offers an intuitive interface. Are you ready to get started?
Free Bonus: Click here to download code resources and a cheat sheet so you can work magic with IPython.
Install and Initiate IPython on Your Machine
It only takes a few steps to install and initiate IPython. First, you’ll need to install Python on your system. You also might want to create and activate a virtual environment instead of installing IPython into your global Python.
Note: IPython comes installed with the Anaconda package. If you’ve installed the full Anaconda package, then you already have IPython.
To install IPython, use pip on the command line:
(venv) C:\Users\User>python -m pip install ipython
Just like that, you should see a message that the installation was successful. That means the package has installed all the dependencies, and you should be able to begin using the interactive shell. If you encounter any issues, please consult the documentation.
After the installation process is finished, you can initiate the interactive shell by executing the command ipython on the command line:
C:\Users\User>ipython
Python 3.11.4 (main, Jun 27 2023, 11:06:35) [Clang 14.0.0 (clang-1400.0.29.202)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.14.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:
You’ll see the above message at the start of the session, confirming the successful installation of IPython on your machine. The shell initiates the first prompt, with In [1] indicating that it’s ready to accept input.
To exit the interactive shell, you can use the exit command, and you’ll switch from IPython to the command line. Now that you have IPython up and running, you’re ready to explore how it can transform your Python workflow. That’s what you’ll discover next.
Improve Your Interactive Python Workflow With IPython
The Python standard shell is a fantastic and versatile tool. However, IPython takes things up a notch by incorporating powerful features that can greatly enhance your coding productivity. While you can explore all of its strengths in the documentation, here are a few noteworthy distinctions that add up to a more user-friendly interface:
- Numbered prompts can give you a stronger understanding of the input code and output results.
- IPython has so many magic commands that the standard Python shell lacks, and they make working in the shell efficient.
- You can access your code history within the shell.
- It makes object introspection and code documentation accessible.
These advantages can make a huge difference in your life as a programmer. You’ll get to know these productivity boosters in the coming sections.
IPython is also available through Jupyter Notebooks. This browser-based interactive interface offers similar features, such as magic commands and numbered input and output. Its decoupled two-process model separates the front-end and back-end components of IPython into distinct processes. This allows the IPython kernel to function independently and handle code execution, namespace management, and communication between the shell and kernel.
Note: IPython isn’t the only interactive shell that you can use. In the Python-verse, options abound, and you can choose your favorite shell out of bpython, ptpython, IDLE, and others.
The standard Python shell allows you to interact with Python on the command line. It permits you to enter statements or expressions one at a time. Then, it executes them and displays the corresponding output:
In the above code examples, you’re able to define two variables, first_name and last_name, and then concatenate the two strings. You can create mini-programs in the Python shell by creating other objects, such as functions and class objects.
The IPython interactive shell works similarly to the Python shell, but it offers a different code layout. Its interface is more expressive than the Python shell, thanks to its numbered input and output prompts, which you can see below:
Above, you start a new IPython session with the command ipython. You can then create variables within the shell. IPython numbers the variables that you’ve defined. Also, the concatenation of the two variables has produced an Out prompt. The code arrangement is more readable with the space separating the prompts.
But what exactly do those numbers mean? Next up, you’ll take a look at IPython’s input and output prompts, one of its key distinguishing features.
Understanding the Input and Output Prompts
One of the most notable differences between the IPython shell and the standard Python shell is the numbered inputs and outputs. You can call them input and output prompts. A prompt consists of one or more lines of code as input. If you get output, then it’ll have the same prompt number as the corresponding input.
To display the numbered inputs and outputs, define an employee profile by creating the following variables:
In [1]: first_name = "Han"
In [2]: last_name = "Solo"
In [3]: department = "Accounts"
In [4]: f"{first_name} {last_name} works in {department}"
Out[4]: 'Han Solo works in Accounts'
In prompts 1, 2, and 3, you define the variables first_name, last_name, and department for the employee Han Solo. The three lines serve as input prompts where you can input or define variables.
In prompt 4, you use an f-string to concatenate the values of the variables. This produces an output line that displays the result of the concatenation. Output lines display the results of executed code or computations.
Note: In IPython, you can access two special variables, In and Out, to list all the Python code you typed and the corresponding outputs.
Compare the IPython shell to the standard Python shell interface:
>>> first_name = "Han"
>>> last_name = "Solo"
>>> department = "Accounts"
>>> f"{first_name} {last_name} works in {department}"
'Han Solo works in Accounts'
The standard Python shell has no numbered input and output prompts. Instead, it uses >>> to represent prompts. Even though this doesn’t interfere with writing and executing code, the interactive shell has a more explicit interface with the help of the input and output prompts.
Note: Later, you’ll learn about magic commands in Python. These behave a bit differently because they don’t generate a code prompt with output. Instead, the output typically displays the return values of executed code.
Overall, the breakdown of code into input and output prompts is more intuitive, which helps you understand and execute your code so that you can more effectively learn Python.
Using Tab Completion
Before you start exploring the functionality of the interactive shell, you’ll want to understand IPython’s tab completion assistance, which is quite different from what the standard shell offers. The IPython shell offers tab completion for any object when you type the first few characters of its name and press the Tab key:
In prompt 5, you enter the first letter of the department variable. When you press Tab, all of the built-in and user-defined objects that start with that letter appear, and you can use the Up, Down, Left, and Right keys to select the one that you intend to use. You then press the Enter button to load the object.
On the other hand, the standard Python shell would show a static list of matching symbols after hitting the Tab key twice.
When you’re working with large libraries or codebases, tab completion can be an efficient tool because you won’t have to scroll back to remember exact function or variable names as long as you know which object you want to use. This can be a time-saver and productivity hack that also reduces errors.
Applying Multiline Code in IPython
Writing multiline code in the standard Python shell can be time-consuming because you have to be aware of Python’s indentation-based syntax.
With the standard Python shell, you’ll have to manually indent each line of a code block with the correct amount of whitespace. For example, here’s how you define a salary_increment() function that adds a 10 percent increment to the employee’s salary within the standard Python shell:
You have to manually add four spaces to comply with Python’s indentation conventions when defining a function. If you forget to apply the indentation, then your code will produce an error, and you’ll have to define the function again.
It’s different in IPython, which automatically applies the indentation to the second and following lines of the function definition:
This is an advantage over Python’s standard shell. IPython will ensure that you don’t have to manually apply indentation after the first line of your function. IPython understands Python’s indentation-based block structure, so its user-friendly interactive shell does it for you.
Embed IPython Into Scripts
One unique feature of IPython is that you can embed it in existing Python scripts, which can offer valuable capabilities in your coding environment. This allows you to have an interactive session within your script, enabling you to explore and interact with variables and execute commands that you’ve defined in your Python file.
To do this, you’ll use the embed() function from the IPython module to launch an interactive session. Write the following code in a Python file named employee.py:
1# employee.py
2
3import IPython
4
5first_name = "Han"
6last_name = "Solo"
7department = "Accounts"
8print(f"{first_name} {last_name}")
9
10IPython.embed()
11
12salary = 1000
Take note of IPython.embed() in line 10. This function will start an IPython session once the execution reaches that line.
Now run the employee.py file like you would run any Python script. Python will execute all the lines of code until it reaches the call to embed(). Then you’ll enter an IPython shell:
C:\Users\User>python employee.py
Han Solo
Python 3.11.4 (main, Jun 27 2023, 11:06:35) [Clang 14.0.0 (clang-1400.0.29.202)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.14.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: first_name
Out[1]: 'Han'
In [2]: last_name
Out[2]: 'Solo'
In [3]: salary
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [3], in <cell line: 1>()
----> 1 salary
NameError: name 'salary' is not defined