23  How to Run Python Code

23.1 Chapter Outline

  • Understanding interpreted vs. compiled languages
  • Running Python in the standard interpreter
  • Using the enhanced IPython interpreter
  • Creating and executing Python scripts
  • Working in interactive environments like Jupyter notebooks
  • Choosing the right environment for your tasks
  • Applying execution techniques to your chatbot project

23.2 Learning Objectives

By the end of this chapter, you will be able to: - Understand the distinction between interpreted and compiled languages - Run Python code using the standard Python interpreter - Use the enhanced features of the IPython interpreter - Create and execute self-contained Python scripts - Work with Jupyter notebooks for interactive development - Choose the appropriate execution environment for different tasks - Run your chatbot project in various environments

23.3 1. Introduction: Many Ways to Run Python

One of Python’s greatest strengths is its flexibility - there are multiple ways to write and execute Python code depending on your specific needs and preferences. Whether you’re quickly testing an idea, developing a complex application, or creating an interactive data analysis, Python offers execution environments suited to each task.

Python is an interpreted language, as opposed to a compiled language like C, Java, or Rust. This fundamental characteristic makes Python highly interactive and accessible, especially for beginners. Let’s explore what this means and how it shapes the ways you can run Python code.

23.4 2. Interpreted vs. Compiled Languages

Before diving into Python’s execution methods, it’s helpful to understand the distinction between interpreted and compiled languages:

23.4.1 Compiled Languages

In compiled languages like C++, Java, or Rust: 1. The entire source code is translated to machine code (or bytecode) before execution 2. The compilation process creates an executable file 3. The resulting program runs independently of the original source code 4. Errors are detected during the compilation phase 5. The program typically runs faster but requires a compilation step before each execution

23.4.2 Interpreted Languages

In interpreted languages like Python, JavaScript, or Ruby: 1. The code is executed line by line at runtime 2. No separate compilation step is required 3. The interpreter reads and executes the source code directly 4. Errors may not be detected until the specific line is executed 5. The program can be more interactive but might run slower than compiled code

This distinction is why Python allows for interactive execution environments where you can type code and see results immediately - a significant advantage for learning, prototyping, and data exploration.

AI Tip: When debugging Python code, use the interactive interpreter to test small sections of your code in isolation. You can copy and paste snippets directly to verify they’re working as expected before integrating them into your larger program.

23.5 3. The Python Interpreter

The most basic way to execute Python code is line by line within the standard Python interpreter. After installing Python, you can start the interpreter by typing python at your system’s command prompt:

$ python
Python 3.10.4 (default, Jun 5 2023, 09:35:24)
[GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Once the interpreter is running (indicated by the >>> prompt), you can type Python commands directly and see immediate results:

>>> 1 + 1
2
>>> x = 5
>>> x * 3
15
>>> print("Hello, Python!")
Hello, Python!
>>> import math
>>> math.sqrt(16)
4.0

The Python interpreter is excellent for: - Testing quick ideas - Exploring language features - Experimenting with libraries - Learning Python syntax - Debugging small code segments

To exit the Python interpreter, type exit() or press Ctrl+D (on Unix/Linux/Mac) or Ctrl+Z followed by Enter (on Windows).

23.6 4. The Enhanced IPython Interpreter

While the standard Python interpreter works well for basic needs, the IPython interpreter offers many enhancements that make interactive Python work more productive and enjoyable. IPython (Interactive Python) is included with most Python distributions like Anaconda, or can be installed separately with pip install ipython.

Launch IPython by typing ipython at the command prompt:

$ ipython
Python 3.10.4 (default, Jun 5 2023, 09:35:24)
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

IPython offers numerous improvements over the standard interpreter:

23.6.1 Enhanced Input/Output

In [1]: 1 + 1
Out[1]: 2

In [2]: x = 5

In [3]: x * 3
Out[3]: 15

23.6.2 Tab Completion

Start typing a command or variable name and press Tab to auto-complete:

In [4]: import mat[TAB]
         math     matplotlib     matrices     ...

In [4]: math.s[TAB]
         math.sin    math.sqrt    math.sinh    ...

23.6.3 Rich Help System

Add a question mark to get help on any object:

In [5]: math.sqrt?
Signature: math.sqrt(x, /)
Docstring: Return the square root of x.
Type:      builtin_function_or_method

23.6.4 System Shell Access

Run shell commands with a leading exclamation mark:

In [6]: !ls
data.csv    myprogram.py    images/   README.md

23.6.5 Magic Commands

Special commands prefixed with % (line magics) or %% (cell magics):

In [7]: %time sum(range(1000000))
CPU times: user 24.5 ms, sys: 0.03 ms, total: 24.6 ms
Wall time: 24.6 ms
Out[7]: 499999500000

IPython is ideal for: - Interactive data exploration - More productive development sessions - Learning complex libraries - Quick system operations without leaving Python

To exit IPython, type exit() or press Ctrl+D.

23.7 5. Self-Contained Python Scripts

For more complex programs or code you want to reuse, you’ll want to save your Python code in files rather than typing it interactively. By convention, Python scripts use the .py file extension.

Here’s how to create and run a simple Python script:

  1. Create a text file named hello.py with the following content:
# hello.py - A simple Python script
print("Hello from Python script!")
name = input("What's your name? ")
print(f"Nice to meet you, {name}!")
  1. Run the script from the command line:
$ python hello.py
Hello from Python script!
What's your name? Alice
Nice to meet you, Alice!

You can also create more complex scripts with multiple functions, classes, and modules:

# calculator.py - A simple calculator script

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Error: Division by zero"
    return a / b

# Main program
print("Simple Calculator")
print("----------------")

first = float(input("Enter first number: "))
second = float(input("Enter second number: "))

print(f"{first} + {second} = {add(first, second)}")
print(f"{first} - {second} = {subtract(first, second)}")
print(f"{first} * {second} = {multiply(first, second)}")
print(f"{first} / {second} = {divide(first, second)}")

Python scripts are excellent for: - Programs meant to be run repeatedly - Code shared with others - Command-line utilities - Automation tasks - Applications with defined inputs and outputs

23.7.1 Making Python Scripts Executable on Unix-Like Systems

On Linux, macOS, and other Unix-like systems, you can make Python scripts directly executable:

  1. Add a “shebang” line at the top of your script:
#!/usr/bin/env python3
# rest of your script follows...
  1. Make the script executable:
$ chmod +x hello.py
  1. Run it directly:
$ ./hello.py

23.8 6. Working with Jupyter Notebooks

Jupyter notebooks represent a revolutionary way to combine code, text, multimedia, and visualizations in a single interactive document. Originally developed for Python (as “IPython notebooks”), they now support many programming languages and have become essential tools for data science, teaching, and interactive computing.

A Jupyter notebook consists of a sequence of cells, which can contain: - Executable code (in Python or other languages) - Formatted text using Markdown - Mathematical equations using LaTeX - Interactive visualizations - Images, videos, and other media

23.8.1 Starting Jupyter

If you have Anaconda installed, you can start Jupyter with:

$ jupyter notebook

Or for the newer Jupyter Lab interface:

$ jupyter lab

This will open a web browser interface where you can create, edit, and run notebooks.

23.8.2 Using Notebooks

A typical workflow in a Jupyter notebook might look like:

  1. Create a markdown cell to explain your analysis:
# Data Analysis Example
This notebook demonstrates loading and analyzing a CSV file of sales data.
  1. Add a code cell to load and explore data:
import pandas as pd
import matplotlib.pyplot as plt

# Load data
sales = pd.read_csv('sales_data.csv')

# Display first few rows
sales.head()
  1. Add a visualization:
# Create a bar chart of sales by region
plt.figure(figsize=(10, 6))
sales.groupby('region')['amount'].sum().plot(kind='bar')
plt.title('Sales by Region')
plt.ylabel('Total Sales ($)')
plt.tight_layout()
plt.show()
  1. Add more explanatory text:
## Findings
The Northeast region shows the highest sales volume, followed by the West.

Jupyter notebooks are ideal for: - Data analysis and exploration - Scientific research - Teaching and learning - Creating rich, interactive narratives - Sharing reproducible research - Documenting code with context

23.8.3 Saving and Sharing Notebooks

Jupyter notebooks are saved with the .ipynb extension. They can be shared in several ways: - As .ipynb files (requires Jupyter to view) - Exported to HTML, PDF, or other formats - Via notebook sharing platforms like GitHub or Google Colab - Using nbviewer (https://nbviewer.org/)

23.9 7. Choosing the Right Environment

Each Python execution environment has its strengths and ideal use cases. Here’s a quick guide to help you choose:

Environment Best for Not ideal for
Python Interpreter Quick tests, learning, exploring Complex programs, saving work
IPython Interactive exploration, enhanced development Production code, sharing with non-technical users
Python Scripts Applications, automation, CLI tools Exploratory analysis, visualization
Jupyter Notebooks Data analysis, teaching, interactive reporting Large applications, production systems

Consider these factors when choosing: - Are you exploring or building? - Do you need to save and reuse your code? - Is visualization important? - Will you share your work with others? - Do you need to incorporate documentation with your code? - Is your task one-time or recurring?

23.10 8. Self-Assessment Quiz

Test your understanding of Python execution environments:

  1. Which of the following describes Python as an interpreted language?
    1. Python code must be compiled before running
    2. Python code is executed line by line at runtime
    3. Python code cannot be saved to files
    4. Python code runs faster than compiled languages
  2. In the standard Python interpreter, which prompt indicates the interpreter is ready for input?
    1. In [1]:
    2. $
    3. >>>
    4. Python>
  3. Which of these is a feature of IPython that isn’t available in the standard Python interpreter?
    1. The ability to define functions
    2. Tab completion
    3. Running arithmetic operations
    4. Importing modules
  4. What file extension is conventionally used for Python script files?
    1. .pyc
    2. .python
    3. .py
    4. .ipy
  5. Which of the following is NOT a typical component of a Jupyter notebook?
    1. Markdown cells for documentation
    2. Code cells that can be executed
    3. Compiled binary output
    4. Interactive visualizations

Answers: 1. b) Python code is executed line by line at runtime 2. c) >>> 3. b) Tab completion 4. c) .py 5. c) Compiled binary output

23.11 Project Corner: Running Your Chatbot in Different Environments

Now that you understand the various ways to run Python code, let’s see how we can adapt our chatbot project to work in different environments.

23.11.1 Chatbot in the Python Interpreter

The interpreter is great for testing small parts of your chatbot:

>>> from chatbot.response_manager import ResponseManager
>>> bot = ResponseManager("TestBot")
>>> bot.get_response("hello there", "Alice")
'Hi there, Alice!'
>>> bot.get_response("what's your name", "Alice")
"I'm TestBot, your chatbot assistant!"

23.11.2 Chatbot as a Script

Create a self-contained script that runs the chatbot from the command line:

# chatbot_cli.py
from chatbot.main import run_chatbot

if __name__ == "__main__":
    print("Starting Chatbot CLI")
    run_chatbot()

Run it with:

$ python chatbot_cli.py

23.11.3 Chatbot in a Jupyter Notebook

Create an interactive notebook version of your chatbot for demonstration or teaching:

# In a Jupyter notebook cell
from chatbot.main import Chatbot
import ipywidgets as widgets
from IPython.display import display, clear_output

# Create a chatbot instance
bot = Chatbot(name="JupyterBot")

# Create input and display widgets
messages = []
output = widgets.Output()
text_input = widgets.Text(description="You:", placeholder="Type a message...")
send_button = widgets.Button(description="Send")

# Display interface
display(output)
input_box = widgets.HBox([text_input, send_button])
display(input_box)

# Define interaction behavior
def on_send_clicked(b):
    user_input = text_input.value
    if not user_input:
        return

    # Clear input box
    text_input.value = ""

    # Add user message to display
    messages.append(f"You: {user_input}")

    # Get bot response
    bot_response = bot.get_response(user_input)
    messages.append(f"JupyterBot: {bot_response}")

    # Update display
    with output:
        clear_output()
        for message in messages:
            print(message)

# Connect button click to handler
send_button.on_click(on_send_clicked)

23.11.4 Chatbot as a Web Application

For a more advanced implementation, you could create a web version using Flask:

# web_chatbot.py
from flask import Flask, render_template, request, jsonify
from chatbot.main import Chatbot

app = Flask(__name__)
bot = Chatbot(name="WebBot")

@app.route('/')
def home():
    return render_template('chat.html')

@app.route('/get_response', methods=['POST'])
def get_bot_response():
    user_input = request.json['message']
    user_name = request.json.get('user_name', 'User')
    response = bot.get_response(user_input)
    return jsonify({'response': response})

if __name__ == '__main__':
    app.run(debug=True)

23.11.5 Choosing the Right Environment for Your Chatbot

Different environments suit different stages of chatbot development:

  1. Interactive Interpreters (Python/IPython): Best for testing individual components, debugging, and rapid development.

  2. Script-Based: Ideal for the final product that users can run easily from the command line.

  3. Jupyter Notebook: Perfect for demonstrating how your chatbot works, testing different scenarios, and collaborative development.

  4. Web Application: Best for sharing your chatbot with a wider audience who may not have Python installed.

As you continue to develop your chatbot, you’ll likely use multiple environments - interactive interpreters during development, scripts for deployment, and perhaps notebooks for documentation and demonstrations.

23.12 Cross-References

AI Tip: When developing complex systems like chatbots, use different Python execution environments for different tasks. Interactive interpreters are great for debugging and testing components, scripts are perfect for deployment, and notebooks excel at documenting your design decisions and showcasing functionality.

23.13 Summary

Python’s flexibility as an interpreted language gives you multiple options for executing code. Each environment has its strengths:

  • The Python interpreter provides a basic but universal way to run Python code interactively
  • The IPython interpreter enhances the interactive experience with features like tab completion
  • Python scripts let you create reusable programs that can be executed repeatedly
  • Jupyter notebooks combine code, text, and visualizations in an interactive document

As you continue your Python journey, you’ll find yourself switching between these environments based on your specific needs. The ability to choose the right tool for each task is a valuable skill that will make you more productive and effective as a Python programmer.

Whether you’re quickly testing an idea in the interpreter, developing a complex application as a script, or creating an interactive analysis in a notebook, Python’s execution flexibility supports a wide range of workflows and use cases.