Introduction to Python and Installation Verification

Week 2: Python Fundamentals - Monday Morning Session

Session Overview

Welcome to our deep dive into Python! Today, we'll explore Python's philosophy, verify our installations, understand Python in containerized environments, work with the interactive shell, run Python scripts, and cover the fundamentals of variables, data types, and basic operations.

Understanding Python's Philosophy

Python was created by Guido van Rossum in the late 1980s and released in 1991. The language was designed with a focus on readability and simplicity, allowing developers to express concepts in fewer lines of code than would be possible in languages like C++ or Java.

At the heart of Python is the "Zen of Python" - a collection of 19 guiding principles that influence the design of the language. You can access these principles by typing import this in your Python interpreter:

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Key Python Philosophies Explained

Real-World Impact of Python's Philosophy

Python's philosophy has made it exceptionally versatile. It's used in:

As we progress through this course, you'll see how Python's design philosophy enables rapid development of robust applications while maintaining clarity and simplicity.

Python Installation Verification

Before diving deeper, we need to ensure Python is correctly installed on our systems. The verification process is like checking if you have the right tools before starting a project - essential for a smooth experience.

Checking Your Python Installation

Open your command line or terminal and try the following commands:

# Check if Python is installed and its version
python --version
# or on some systems:
python3 --version

You should see output similar to:

Python 3.10.4

For our course, we'll be using Python 3.10 or newer, as it includes important modern features and improvements.

Verifying Python's Location

To see where Python is installed on your system:

# On Windows
where python

# On macOS/Linux
which python
which python3

This command returns the path to your Python executable, which is useful for understanding your environment setup.

Testing Python's Core Functionality

Let's verify Python is working correctly by testing some basic operations:

# Start the Python interpreter
python
# or
python3

# Try some basic operations in the interpreter
>>> 2 + 2
4
>>> print("Hello, Python World!")
Hello, Python World!
>>> exit()  # To exit the interpreter

Checking Installed Packages

Python's package manager, pip, should be included with your installation. Verify it works:

# Check pip version
pip --version
# or
pip3 --version

# List installed packages
pip list

Troubleshooting Common Installation Issues

Analogy: Python Installation as Setting Up a Workshop

Think of Python installation like setting up a woodworking workshop:

  • The Python interpreter is your workbench - the foundation for all your projects
  • Standard libraries are like your basic tools (hammers, saws, drills)
  • pip is your supplier, allowing you to order specialized tools (packages)
  • PATH configuration is like ensuring you can easily access all areas of your workshop
  • Virtual environments (which we'll cover) are like having separate workbenches for different projects, preventing tool conflicts

Just as a carpenter verifies their tools are working before starting a project, we verify our Python installation before coding.

Python in Docker Containers

Docker containers provide isolated, consistent environments for developing and deploying Python applications. This approach solves the classic "it works on my machine" problem by packaging your code with all its dependencies.

Benefits of Containerized Python

Verifying Python in a Docker Container

If you're using Docker, you can verify Python within a container:

# Pull an official Python image
docker pull python:3.10

# Run Python in a container
docker run -it python:3.10 python --version

# Start an interactive Python session in a container
docker run -it python:3.10

Creating a Simple Python Container

Let's create a basic Dockerfile for a Python application:

Create a file named Dockerfile in your project directory with the following content:

# Base image
FROM python:3.10-slim

# Set working directory
WORKDIR /app

# Copy requirements first (for better caching)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY . .

# Command to run when container starts
CMD ["python", "app.py"]

And create a simple app.py file:

print("Hello from Python in Docker!")
import sys
print(f"Python version: {sys.version}")

Build and run the container:

# Build the image
docker build -t my-python-app .

# Run the container
docker run my-python-app

Analogy: Docker Containers as Food Delivery Boxes

Think of Docker containers like those meal kit delivery services:

  • The recipe (your code) comes with exactly the right ingredients (dependencies)
  • Everything is pre-measured and packaged together
  • It works the same way regardless of whose kitchen it's prepared in
  • Different meals (applications) don't interfere with each other
  • You can easily make the same meal again later with consistent results

Real-World Example: Microservice Architecture

Major companies like Netflix and Spotify use containerized Python microservices to build scalable architectures. Each service runs in its own container, allowing teams to develop, deploy, and scale independently. For instance, one Python container might handle user authentication while another processes recommendations, all communicating via well-defined APIs.

Interactive Python (REPL) Basics

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.

Starting the REPL

To start the interactive interpreter:

# Simple way
python
# or
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.

REPL Basics

The REPL operates in a cycle:

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

Using the REPL Effectively

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

>>> name = "Python Learner"
>>> print(f"Hello, {name}!")
Hello, Python Learner!

>>> # Multiline statements need continuation
>>> if True:
...     print("This is true")
...     print("And this runs too")
...
This is true
And this runs too

>>> # The REPL automatically prints expression results
>>> [i**2 for i in range(5)]  # A list comprehension
[0, 1, 4, 9, 16]

Special REPL Features

>>> 10 * 20
200
>>> _ + 5  # Using the last result
205

>>> import math
>>> math.  # Press Tab here to see all available methods
>>> help(math.sqrt)  # Get help on a specific function

IPython: An Enhanced REPL

Consider using IPython for an improved interactive experience:

# Install IPython
pip install ipython

# Launch IPython
ipython

IPython offers syntax highlighting, better tab completion, and many other enhancements.

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

It's immediate feedback makes it perfect for learning - like having a tutor who instantly checks your work.

Real-World Applications of the REPL

Data scientists regularly use enhanced REPLs like Jupyter Notebooks for exploratory data analysis. They can run code segments, visualize results, and refine their approach iteratively. Software engineers use the REPL to test small code snippets before incorporating them into larger projects, verifying behavior without creating full test files.

Running Python Scripts

While the REPL is great for experimentation, most Python code is written in script files that can be executed as complete programs.

Creating a Python Script

Python scripts are simply text files with a .py extension. Create a file named hello_world.py with the following content:

# This is a comment in Python
print("Hello, World!")
print("Welcome to Python programming!")

# Variables and simple calculation
name = "Python Learner"
experience_years = 5
print(f"{name} has {experience_years} years of programming experience.")
print(f"In 2 more years, they will have {experience_years + 2} years of experience.")

Running Scripts from the Command Line

# Basic execution
python hello_world.py
# or
python3 hello_world.py

Script Execution Modes

Python scripts can be run in different ways:

For executable scripts on Unix-based systems, add a shebang line and make the file executable:

#!/usr/bin/env python3
print("This script is directly executable!")

Then run:

chmod +x script_name.py
./script_name.py

Command-line Arguments

Scripts can accept arguments from the command line. Create a file named greet.py:

import sys

if len(sys.argv) > 1:
    name = sys.argv[1]
    print(f"Hello, {name}!")
else:
    print("Hello, stranger! Please provide your name as an argument.")

Run it with:

python greet.py Alice

Importing Scripts as Modules

Python scripts can also be imported as modules. Create a file math_helpers.py:

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

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

if __name__ == "__main__":
    # This code only runs when the script is executed directly
    print("Testing math functions:")
    print(f"5 + 3 = {add(5, 3)}")
    print(f"4 * 6 = {multiply(4, 6)}")

The if __name__ == "__main__": block is a common pattern that allows a file to function both as a script and as an importable module.

Analogy: Scripts vs. REPL

If the REPL is like having a conversation, then scripts are like writing a letter:

  • Scripts are prepared in advance (written completely before execution)
  • They can be reviewed, edited, and perfected before being "sent" (executed)
  • They can be saved and re-used many times
  • They can be shared with others to run exactly the same way

The REPL is great for exploration and quick tests (like a phone call), while scripts are better for complete programs and automation (like a detailed written plan).

Real-World Script Examples

In production environments, Python scripts handle critical automation tasks. For example, a deployment script might:

  1. Pull the latest code from version control
  2. Run tests to verify functionality
  3. Build application assets
  4. Upload to servers
  5. Switch traffic to the new version
  6. Send notification emails to the team

Companies like Instagram use thousands of Python scripts to automate everything from content moderation to server management.

Wrapping Up and Looking Ahead

Today we've covered the foundations of Python, including its philosophy, installation verification, working with Python in containers, using the interactive REPL, and running Python scripts. These fundamentals will serve as building blocks for everything else we learn in this course.

In our next session, we'll dive deeper into Python's data model, exploring variables, data types, and basic operations in greater detail.

Practice Exercises

  1. Verify your Python installation and try running code in the REPL.
  2. Create a simple script that calculates and displays your age in days, hours, and minutes.
  3. If using Docker, build a container that runs your script.
  4. Explore one principle from the Zen of Python and write a small script that demonstrates it.

Additional Resources