Introduction

🐍 Introduction to Python

This lesson covers everything you need to get Python up and running — across three different environments — and establishes the conventions and tools used throughout all subsequent lessons. Skip what you already know, focus on what's new.

⚡ Coming from Java / JavaScript Three key mindset shifts from your existing experience: (1) No compilation step — Python files run directly as source. (2) Package management is closer to npm than Maven — a single tool (pip) installs everything, and per-project isolation is handled by virtual environments rather than a project-level node_modules. (3) The command is python or python3 depending on platform — there is no JVM or Node runtime to install separately.
🚀 FastAPI relevance — FOUNDATION Everything in this lesson is prerequisite for FastAPI. Virtual environments ensure your FastAPI project dependencies don't conflict with system packages. The web development packages listed here are the exact stack you'll use: FastAPI, Uvicorn, SQLAlchemy, Pydantic, and Alembic.

🔍 What is Python?

Python is a general-purpose, interpreted, dynamically typed programming language first released in 1991. It consistently ranks as one of the world's most popular languages and is the dominant choice for web backends, data science, automation, AI/ML, and scripting.

Interpreted
No compilation step
Python source files (.py) run directly. The interpreter reads and executes them line by line. No javac, no build tool — just write and run. This makes iteration very fast.
Dynamically typed
Types at runtime, not compile time
Variables don't have declared types. Type errors appear at runtime rather than compile time. Optional type hints (covered in the Variables lesson) add static analysis without changing runtime behaviour.
Batteries included
Rich standard library
Python ships with an extensive standard library — file I/O, JSON, HTTP, dates, maths, databases, email, and much more — all without any additional installs. Third-party packages via pip extend this further.
Ecosystem
PyPI — 500,000+ packages
The Python Package Index (PyPI) hosts over half a million packages. Web frameworks (FastAPI, Django, Flask), data tools (pandas, numpy), and AI libraries (TensorFlow, PyTorch) are all a single pip install away.

🔢 Python Versions

Always use Python 3. Python 2 reached end-of-life in January 2020 and should not be used for new projects. Aim for Python 3.11 or 3.12 for best performance and feature support.

Check Your Python Version

🪟 Windows 11
# In PowerShell or Command Prompt python --version python -V # If both Python 2 & 3 installed py -3 --version
On Windows the command is usually python, not python3.
🍓 Raspberry Pi 5 — Debian Bookworm
# In Terminal python3 --version python3 -V # Check pip version too pip3 --version
Use python3 — plain python may not exist or may be Python 2.
🎩 Red Hat Linux (RHEL / Fedora / Rocky / Alma)
# In Terminal python3 --version python3 -V # Check available versions alternatives --list | grep python
Use python3. On RHEL 8+ the default is Python 3.6–3.11 depending on release.

⬇️ Installing Python

🪟 Windows 11

Python is not installed by default on Windows. You have three options — the official installer is recommended.

## Option 1: Official installer (recommended) # 1. Go to https://python.org/downloads # 2. Download the latest Python 3.x Windows installer # 3. Run the installer — TICK "Add Python to PATH" before clicking Install # 4. Verify in a new PowerShell window: python --version ## Option 2: winget (Windows Package Manager — terminal install) winget install Python.Python.3.12 ## Option 3: Microsoft Store # Search "Python" in the Microsoft Store — convenient but some tools behave differently ## After installing — verify pip is available pip --version
⚠ If you forget to tick "Add Python to PATH" during install, re-run the installer and choose "Modify", then enable the PATH option.
🍓 Raspberry Pi 5 — Debian Bookworm

Python 3 is pre-installed on Raspberry Pi OS (Bookworm). You may need to install pip and venv support separately.

## Update package lists first (always good practice) sudo apt update && sudo apt upgrade -y ## Install Python 3, pip, and venv support sudo apt install -y python3 python3-pip python3-venv python3-full ## Verify python3 --version pip3 --version ## Optional: install a specific newer version via deadsnakes PPA ## (Bookworm ships Python 3.11 — this is usually sufficient) # sudo add-apt-repository ppa:deadsnakes/ppa # sudo apt install python3.12
⚠ Debian Bookworm enforces PEP 668 — you cannot pip install packages globally. Always use a virtual environment (covered below).
🎩 Red Hat Linux (RHEL 8+ / Fedora / Rocky Linux / AlmaLinux)

Python 3 is available via dnf (RHEL 8+/Fedora) or yum (older systems). RHEL may require enabling the AppStream repository.

## RHEL 8+ / Rocky Linux / AlmaLinux / Fedora — using dnf sudo dnf install -y python3 python3-pip ## For RHEL 7 / CentOS 7 — using yum sudo yum install -y python3 python3-pip ## Install a specific version (Fedora / EPEL) sudo dnf install -y python3.11 # or sudo dnf install -y python3.12 ## If pip is not available via dnf, install manually curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python3 get-pip.py --user ## Verify python3 --version pip3 --version
On RHEL-based systems, python3 may point to 3.6 even on recent releases. Install a specific version if you need 3.11+.

🏖️ Virtual Environments

What Is a Virtual Environment?

A virtual environment is an isolated, self-contained Python installation for a specific project. It has its own copy of pip and its own set of installed packages — completely separate from the system Python and from every other project.

The Problem
Dependency conflicts
Project A needs requests==2.28. Project B needs requests==2.31. Without isolation they can't coexist. Virtual environments solve this by giving each project its own package directory.
The Solution
One venv per project
Each project lives in its own folder with an activated virtual environment. Installing packages only affects that environment. Deleting the venv folder removes all its packages cleanly.
Node.js equivalent
Like node_modules per project
If you know Node.js, a venv is conceptually similar to node_modules — project-local dependencies. The key difference is you must explicitly activate the environment before use.
Linux enforcement
PEP 668 — required on modern Linux
Debian Bookworm (your Pi) and modern Red Hat distributions block global pip install to protect system packages. Virtual environments are not just recommended — they are required on these systems.

Creating a Virtual Environment

🪟 Windows 11
# Navigate to your project folder cd C:\Projects\mealplanner # Create the venv (named "venv" by convention) python -m venv venv # The venv folder is created: # mealplanner/ # venv/ # Scripts/ # Lib/ # ...
🍓 Raspberry Pi 5
# Navigate to your project folder cd ~/projects/mealplanner # Create the venv python3 -m venv venv # If python3-venv is not installed: sudo apt install python3-venv python3 -m venv venv
🎩 Red Hat Linux
# Navigate to your project folder cd ~/projects/mealplanner # Create the venv python3 -m venv venv # If venv module missing: sudo dnf install python3-virtualenv python3 -m venv venv

Activating & Deactivating

⚠ Always activate before working. A virtual environment does nothing until it is activated. Once active, python and pip point to the venv's versions — not the system ones. Your terminal prompt changes to show (venv) when it is active.
🪟 Windows 11
# PowerShell .\venv\Scripts\Activate.ps1 # Command Prompt (cmd.exe) venv\Scripts\activate.bat # Prompt changes to: # (venv) PS C:\Projects\mealplanner> # Deactivate deactivate
PowerShell may block scripts — run Set-ExecutionPolicy RemoteSigned -Scope CurrentUser once to allow it.
🍓 Raspberry Pi 5
# Activate source venv/bin/activate # Prompt changes to: # (venv) pi@raspberrypi:~/projects/mealplanner$ # Now use python (not python3) python --version # Deactivate deactivate
Once active, use python and pip — the venv rewires these commands automatically.
🎩 Red Hat Linux
# Activate source venv/bin/activate # Prompt changes to: # (venv) [user@host mealplanner]$ # Now use python and pip python --version # Deactivate deactivate
Identical to Debian/Pi — Linux activation is consistent across distros.

📦 pip — Python's Package Manager

pip is Python's equivalent of npm (Node.js) or Maven (Java). It downloads and installs packages from PyPI — the Python Package Index at pypi.org. Always activate your virtual environment before running pip.

Essential pip Commands
These commands are the same on all three platforms once your virtual environment is activated.
# Install a package pip install fastapi # Install a specific version pip install fastapi==0.111.0 # Install minimum version pip install fastapi>=0.100.0 # Install multiple packages at once pip install fastapi uvicorn sqlalchemy # Upgrade a package to latest pip install --upgrade fastapi # Uninstall a package pip uninstall fastapi # List all installed packages in this venv pip list # Show details about a specific package pip show fastapi # Export installed packages to a requirements file pip freeze > requirements.txt # Install all packages from a requirements file # (used when setting up a project someone else created) pip install -r requirements.txt
requirements.txt — Sharing Your Dependencies
The requirements.txt file is the Python equivalent of package.json — it records every package your project needs so that anyone else (or you on another machine) can recreate the same environment exactly. Always commit this file to version control.
# Generate it (run with venv active) pip freeze > requirements.txt # Example requirements.txt contents: # fastapi==0.111.0 # uvicorn[standard]==0.30.1 # sqlalchemy==2.0.30 # pydantic==2.7.1 # alembic==1.13.1 # Recreate environment on another machine: python -m venv venv # (activate venv, then:) pip install -r requirements.txt

🌐 Installing Web Development Packages

The packages below form the core stack for Python web development — particularly for building a FastAPI application like the meal planner. Install them inside your activated virtual environment.

Install the Full Web Development Stack
Run this with your virtual environment active. This is the same command on all three platforms.
# Core FastAPI stack pip install fastapi uvicorn[standard] # Database ORM and migrations pip install sqlalchemy alembic # HTTP client (for calling external APIs) pip install httpx requests # Templating engine (for server-rendered HTML) pip install jinja2 # File upload support (required by FastAPI for multipart forms) pip install python-multipart # Environment variable management pip install python-dotenv # Or install them all in one line: pip install fastapi "uvicorn[standard]" sqlalchemy alembic httpx requests jinja2 python-multipart python-dotenv
PackagePurposeNotes
fastapiWeb framework — routes, validation, API docsBrings Pydantic and Starlette as dependencies
uvicorn[standard]ASGI server — runs your FastAPI appThe equivalent of Node's built-in HTTP server
pydanticData validation using type hintsInstalled automatically with FastAPI
sqlalchemyDatabase ORM — work with databases in PythonLike Hibernate for Java
alembicDatabase migration toolLike Flyway/Liquibase for Java
httpxAsync-capable HTTP clientModern alternative to requests — async support
requestsSimple synchronous HTTP clientLike Java's HttpClient or JS's fetch
jinja2HTML templating engineLike Thymeleaf (Java) or Handlebars (JS)
python-multipartForm and file upload parsingRequired when accepting file uploads in FastAPI
python-dotenvLoad .env files as environment variablesKeep secrets out of source code
psycopg2-binaryPostgreSQL database driverInstall if using PostgreSQL
aiosqliteAsync SQLite driverGood for local development without a server
pytestTesting frameworkThe standard Python testing tool
🪟 Windows 11 — PostgreSQL driver note
# psycopg2-binary usually works on Windows pip install psycopg2-binary # If it fails, try the binary wheel: pip install psycopg2-binary --only-binary :all:
🍓 Raspberry Pi 5 — build tools
# Some packages need build tools sudo apt install -y python3-dev \ libpq-dev gcc build-essential # Then install normally in venv pip install psycopg2-binary
🎩 Red Hat — build dependencies
# Install build tools and PostgreSQL headers sudo dnf install -y python3-devel \ postgresql-devel gcc # Then install in venv pip install psycopg2-binary

⌨️ The Python REPL — Interactive Mode

The REPL (Read-Eval-Print Loop) is an interactive Python shell. Type a Python expression, press Enter, see the result immediately. It's invaluable for testing ideas, exploring APIs, and debugging — there's no equivalent quick-feedback loop in Java.

🪟 Windows 11
# Launch REPL python # With specific version py -3.12 # Exit the REPL exit() # or Ctrl+Z then Enter
🍓 Raspberry Pi 5
# Launch REPL python3 # or (with venv active) python # Exit the REPL exit() # or Ctrl+D
🎩 Red Hat Linux
# Launch REPL python3 # or (with venv active) python # Exit the REPL exit() # or Ctrl+D
What the REPL Looks Like
The >>> prompt means Python is waiting for input. Results print immediately — no print statement needed for single expressions.
Python 3.12.3 (main, Apr 9 2025, 08:09:14) Type "help", "copyright", "credits" or "license" for more information. >>> 2 + 2 4 >>> name = "Philip" >>> f"Hello, {name}!" 'Hello, Philip!' >>> ingredients = ["milk", "eggs", "flour"] >>> len(ingredients) 3 >>> [i.upper() for i in ingredients] ['MILK', 'EGGS', 'FLOUR'] >>> exit()

▶️ Running Python Scripts

Python scripts are plain text files with a .py extension. Run them from the terminal — always with your virtual environment active if the script uses installed packages.

🪟 Windows 11
# Run a script python script.py python main.py # With Python Launcher py -3 script.py py -3.12 script.py # Run a module as a script python -m uvicorn main:app --reload
🍓 Raspberry Pi 5
# Run a script python3 script.py # or (with venv active) python script.py # Run a FastAPI app python -m uvicorn main:app \ --reload --host 0.0.0.0
🎩 Red Hat Linux
# Run a script python3 script.py # or (with venv active) python script.py # Run a FastAPI app python -m uvicorn main:app \ --reload --host 0.0.0.0

🖥️ IDE & Editor Recommendations

VS Code
Free
The most popular choice for Python. Install the official Python extension by Microsoft for IntelliSense, debugging, venv auto-detection, and Jupyter notebook support. Works excellently on all three platforms.
🪟 Windows · 🍓 Raspberry Pi · 🎩 Red Hat
PyCharm
Free (Community)
JetBrains' dedicated Python IDE — if you've used IntelliJ IDEA for Java this will feel instantly familiar. The Community edition is free and excellent for FastAPI development. Professional adds database tools.
🪟 Windows · 🎩 Red Hat
Thonny
Free
Lightweight IDE designed for beginners — ships pre-installed on Raspberry Pi OS. Simple debugger, built-in pip manager, and a clean interface. Good for getting started quickly on the Pi without heavy setup.
🍓 Raspberry Pi (pre-installed)
VS Code — Python Extension Setup
After installing VS Code, install the Python extension and point it to your virtual environment.
# Install VS Code Python extension via command line code --install-extension ms-python.python code --install-extension ms-python.pylance # type checking code --install-extension ms-python.debugpy # debugging # Open your project folder code . # Select interpreter: Ctrl+Shift+P → "Python: Select Interpreter" # → Choose the venv interpreter (./venv/bin/python or ./venv/Scripts/python.exe) # VS Code will auto-activate your venv in its integrated terminal

📁 Python Project Structure

Python doesn't enforce a project layout, but conventions exist. Below is a recommended structure for a FastAPI project — including the meal planner you're planning to build.

mealplanner/ ← project root │ ├── venv/ ← virtual environment — never commit to git! │ ├── app/ ← your application package │ ├── __init__.py ← makes app/ a Python package (can be empty) │ ├── main.py ← FastAPI app entry point │ ├── routers/ ← route handlers (one file per feature) │ │ ├── recipes.py │ │ ├── inventory.py │ │ └── meal_plan.py │ ├── models/ ← database models (SQLAlchemy) │ │ └── ingredient.py │ ├── schemas/ ← Pydantic schemas (request/response shapes) │ │ └── ingredient.py │ └── db/ ← database connection setup │ └── database.py │ ├── tests/ ← pytest test files │ └── test_recipes.py │ ├── .env ← secrets & config — NEVER commit to git! ├── .gitignore ← include venv/ and .env here ├── requirements.txt ← project dependencies — always commit this └── README.md
The .gitignore File — What Not to Commit
Your venv/ folder and .env file must never go into version control. Add a .gitignore to your project root from the start.
# .gitignore for a Python project venv/ .env *.env __pycache__/ *.pyc *.pyo .pytest_cache/ .mypy_cache/ dist/ build/ *.egg-info/
⚠ Common Setup Mistakes:

Forgetting to activate the virtual environment — the single most common issue. If pip install fastapi seems to have no effect, or import fastapi fails, you almost certainly forgot to activate the venv. Check your prompt — it should show (venv). Fix: source venv/bin/activate (Linux/Mac) or .\venv\Scripts\Activate.ps1 (Windows).

python vs python3 — on Linux and the Pi, always use python3 when outside a virtual environment. Inside an activated venv, both python and python3 work. On Windows, python is the standard command. This trips up everyone who switches between platforms.

Installing packages globally on Linux — on Debian Bookworm (Pi) and modern Red Hat, running sudo pip install anything will either fail with a PEP 668 error or break system packages. Always use a virtual environment. If you see "externally managed environment" in an error message, this is the cause.

Committing venv/ or .env to git — the venv/ folder can be hundreds of megabytes and is machine-specific. The .env file contains secrets. Neither should ever be in version control. Use requirements.txt to share dependencies instead.