Interactive Python (REPL) Basics

Week 2: Python Fundamentals - Interactive Python Deep Dive

Session Overview

Welcome to our deep dive into Interactive Python! Today, we'll explore the Python Read-Evaluate-Print Loop (REPL), a powerful environment for interactive coding, experimentation, and learning. We'll master the REPL interface, learn advanced techniques for effective interaction, and discover how professional developers leverage the REPL in real-world scenarios.

Understanding the Python REPL

The Python interpreter can be used interactively through what's known as the REPL (Read-Evaluate-Print Loop). This powerful tool allows you to execute Python code line by line, immediately seeing the results without having to create, save, and run a full script file.

What is a REPL?

REPL stands for Read-Evaluate-Print Loop, describing the cycle of interaction:

  1. Read: The interpreter reads the input you type
  2. Evaluate: It evaluates/executes the code
  3. Print: It prints the result to the screen
  4. Loop: It returns to the prompt, waiting for more input

This immediate feedback loop makes the REPL perfect for learning, testing ideas, debugging, and exploring Python's capabilities.

Analogy: REPL as a Conversation

Using the REPL is like having a conversation with Python:

  • You say something (input code)
  • Python thinks about it (evaluates)
  • Python responds (shows the result)
  • Then waits for you to say something else

In contrast, running a script is more like sending a letter - you write everything at once, send it off, and get a response later. The REPL's immediate feedback makes it perfect for learning - like having a tutor who instantly checks your work.

Starting the Python REPL

Launching from the Command Line

To start the interactive interpreter:

# On most systems
python

# On systems with both Python 2 and 3 installed
python3

You'll see something like:

Python 3.10.4 (main, Mar 31 2022, 08:41:55) [GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> prompt indicates the interpreter is ready for your input.

Alternative Ways to Access the REPL

REPL in Different Environments

The REPL behaves slightly differently depending on where you run it:

Basic REPL Interaction

Simple Expressions and Statements

Let's start with some basic interactions:

>>> 2 + 3 * 4  # Python follows mathematical order of operations
14

>>> "Hello" + " " + "world!"  # String concatenation
'Hello world!'

>>> print("Hello, Python!")  # Using the print function
Hello, Python!

>>> x = 10  # Variable assignment
>>> x * 2    # Using the variable
20

Expression Results vs. Statements

The REPL automatically displays the result of expressions, but not statements:

>>> 42  # Expression - result is displayed
42

>>> x = 42  # Statement - no result displayed
>>> print(x)  # Statement with side effect (printing)
42

>>> [i for i in range(5)]  # List comprehension (an expression)
[0, 1, 2, 3, 4]

Multiline Code in the REPL

For code blocks that span multiple lines, the prompt changes to ... for continuation lines:

>>> if True:
...     print("This is true")
...     print("And this runs too")
...
This is true
And this runs too

>>> for i in range(3):
...     print(f"Iteration {i}")
...
Iteration 0
Iteration 1
Iteration 2

To end a multiline block, press Enter on an empty line (after the ... prompt).

Function and Class Definitions

You can define functions and classes directly in the REPL:

>>> def square(x):
...     """Return the square of a number."""
...     return x * x
...
>>> square(4)
16

>>> class Point:
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...     def __str__(self):
...         return f"Point({self.x}, {self.y})"
...
>>> p = Point(3, 4)
>>> p
<__main__.Point object at 0x7f1234567890>
>>> print(p)
Point(3, 4)

Special REPL Features

The Underscore Variable (_)

The REPL automatically stores the last expression result in the special _ variable:

>>> 10 * 20
200
>>> _ + 5  # Using the last result
205
>>> print(f"The previous result plus 10 is {_ + 10}")
The previous result plus 10 is 215

This is extremely useful for continuing calculations or reusing values without assigning them to variables.

Tab Completion

Most Python REPLs support tab completion, which helps you write code faster and explore available options:

>>> import math
>>> math.  # Press Tab here to see all available methods
math.acos       math.degrees    math.log10      math.sin
math.acosh      math.dist       math.log1p      math.sinh
math.asin       math.e          math.log2       math.sqrt
...

>>> st  # Press Tab to complete
StopIteration   str(            staticmethod(

Tab completion works for module names, attributes, methods, and even filenames in some cases.

Command History

Navigate through your command history with the up and down arrow keys:

Introspection with help()

The built-in help() function provides documentation for objects:

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    ...

>>> help(str.split)
Help on method_descriptor:

split(...)
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    Return a list of the words in S, using sep as the
    delimiter string...

You can also enter interactive help mode by typing help() without arguments.

dir() for Discovery

The dir() function shows available attributes and methods for an object:

>>> dir(str)
['__add__', '__class__', '__contains__', ..., 'capitalize', 'casefold', 'center', ...]

>>> dir()  # Without arguments, shows names in current scope
['__annotations__', '__builtins__', '__doc__', ..., 'x', 'square', 'Point', 'p']

Analogy: REPL Features as Exploration Tools

Think of the REPL features as tools for exploring a new city:

  • Tab completion is like having a map that shows all possible streets from your current location
  • Command history is like being able to instantly return to places you've already visited
  • help() is like having a detailed guidebook for any landmark you encounter
  • dir() is like having a list of all attractions in your current neighborhood
  • The _ variable is like having a teleporter to your last location

These tools transform the REPL from a simple command prompt into a powerful environment for learning and discovery.

Enhanced REPLs: IPython and Beyond

IPython: A Supercharged REPL

IPython is an enhanced interactive Python shell with many additional features:

# Install IPython
pip install ipython

# Launch IPython
ipython

Key IPython features include:

IPython Magic Commands

Magic commands provide special functionality in IPython:

%run script.py      # Run a Python script within IPython
%timeit expr        # Time the execution of an expression
%paste             # Paste and execute clipboard content
%history           # Show command history
%matplotlib inline  # Set up matplotlib for inline plotting
%who               # List all variables in namespace
%load file.py      # Load a script into the current session

Jupyter Notebooks

Jupyter Notebooks provide a web-based REPL environment that combines code, output, visualizations, and documentation:

# Install Jupyter
pip install notebook

# Launch Jupyter Notebook
jupyter notebook

Benefits of Jupyter Notebooks:

VS Code Interactive Window

VS Code's Python extension provides an interactive window that combines script editing with REPL-like execution:

Advanced REPL Techniques

Importing and Reloading Modules

When working with your own modules in the REPL, you'll often need to reload after changes:

>>> import my_module  # Initial import
>>> # After changing my_module.py
>>> import importlib
>>> importlib.reload(my_module)  # Reload the module with changes

# In IPython, you can use the %autoreload magic
%load_ext autoreload
%autoreload 2  # Automatically reload all modules before execution

Debugging in the REPL

The REPL is excellent for interactive debugging:

>>> import pdb
>>> pdb.run('my_function(arg1, arg2)')  # Run with debugger

# In IPython, use %debug after an exception
try:
    result = problematic_function()
except Exception:
    %debug  # Start post-mortem debugging

Saving and Loading REPL Sessions

You can save your work from a REPL session:

# In IPython
%history -f session.py  # Save commands to a file

# In standard REPL, use the readline module
import readline
readline.write_history_file('history.txt')

Customizing the REPL Environment

You can customize your REPL startup environment:

Example startup file (~/.pythonrc):

# Python startup file
import math
import os
import sys
import datetime

# Define useful functions
def cls():
    os.system('cls' if os.name=='nt' else 'clear')

# Welcome message
print(f"Python {sys.version.split()[0]} on {sys.platform}")
print(f"Today is {datetime.datetime.now().strftime('%Y-%m-%d')}")
print("Type help(), copyright, credits or license for more information.")

REPL in the Real World

Data Exploration and Analysis

Data scientists extensively use REPLs (particularly Jupyter Notebooks) for:

# Example of data exploration in IPython
import pandas as pd
import matplotlib.pyplot as plt

# Load and examine data
df = pd.read_csv('data.csv')
df.head()
df.describe()

# Create a visualization
%matplotlib inline
df.plot(kind='scatter', x='feature1', y='feature2')
plt.title('Feature Relationship')
plt.show()

API Testing and Exploration

Developers use the REPL to explore and test APIs:

>>> import requests
>>> response = requests.get('https://api.example.com/data')
>>> response.status_code
200
>>> data = response.json()
>>> data['results'][0]['name']
'Example Item'

# Try different parameters
>>> params = {'category': 'electronics', 'limit': 5}
>>> requests.get('https://api.example.com/data', params=params).json()

Software Prototyping

The REPL allows developers to quickly test concepts and algorithms:

System Administration and Automation

System administrators use the Python REPL for:

>>> import os
>>> import glob
>>> # Find all large log files
>>> [f for f in glob.glob('*.log') if os.path.getsize(f) > 1000000]
['application.log', 'error.log']

>>> # Check disk usage
>>> import shutil
>>> shutil.disk_usage('/')
usage(total=250790436864, used=81132462080, free=169657974784)

Analogy: The REPL as a Laboratory

Think of the REPL as a scientific laboratory where you can:

  • Run small experiments (code snippets) to test hypotheses
  • Observe results immediately and adjust your approach
  • Mix different components to see how they interact
  • Document findings (with enhanced REPLs like Jupyter)
  • Share your experimental setup and results with colleagues

Just as scientific discovery often happens through iterative experimentation, coding breakthroughs can emerge through interactive REPL sessions.

REPL Best Practices

Effective REPL Workflows

REPL-Driven Development

Some developers use a workflow called "REPL-Driven Development":

  1. Experiment and develop in the REPL
  2. When code works, save it to script files
  3. Organize into functions, classes, and modules
  4. Write tests based on observed behavior
  5. Repeat for new features

Combining REPLs with Scripts

The REPL and script files complement each other:

REPL Limitations and When to Avoid It

While powerful, the REPL isn't ideal for:

Use the REPL as a development and learning tool, but transition to proper scripts and modules for production code.

Practical REPL Exercises

Exercise 1: REPL Exploration

  1. Start the Python REPL
  2. Import the random module
  3. Use dir(random) to see available functions
  4. Use help(random.choice) to learn about a function
  5. Create a list of items and use random.choice() to select one
  6. Experiment with other random functions based on what you discovered

Exercise 2: Interactive Data Analysis

In an IPython or Jupyter environment:

  1. Create a list of numbers (e.g., data = [random.randint(1, 100) for _ in range(50)])
  2. Calculate basic statistics (min, max, mean, median, standard deviation)
  3. Create a histogram of the data
  4. Find all numbers divisible by 3
  5. Create a new list with each value squared

Exercise 3: REPL-Driven Development

  1. In the REPL, develop a function that counts word frequency in a text string
  2. Test it with various inputs and edge cases
  3. When it works correctly, save it to a script file
  4. Import the script back into the REPL
  5. Extend your function with additional features (e.g., ignoring case, excluding stopwords)

Wrapping Up and Next Steps

Today we've explored the Python REPL in depth, from basic usage to advanced techniques and real-world applications. The interactive nature of the REPL makes it an invaluable tool for learning, experimentation, and rapid development.

Key Takeaways

Next Steps for REPL Mastery

  1. Install and explore IPython for an enhanced REPL experience
  2. Try Jupyter Notebooks for literate programming with Python
  3. Create a custom PYTHONSTARTUP file to personalize your REPL
  4. Practice using the REPL for exploring new libraries
  5. Incorporate REPL-driven development into your workflow

Additional Resources

In our next session, we'll explore how to create and run complete Python scripts, building on the interactive exploration skills you've learned today.