Python Zero to Hero: From First Script to Media, ML and GenAI

Start with nothing but curiosity and finish building data pipelines, media tools, machine learning models and generative AI apps. Every runnable example is a complete single-file program you can copy and run.

12 Modules95 Examples51 RunnablePython 3.12

Setting up Python and the examples

Install Python 3.12, create an isolated environment, install the libraries used later in the course, and keep API keys out of your code. Other modules link back here when a library or tool is needed.

Install Python 3.12

Download Python 3.12 from python.org/downloads or use your system package manager. On Windows tick Add python.exe to PATH in the installer. On Windows the launcher command is py; on macOS and Linux the command is python3.

Windows (PowerShell)

winget install Python.Python.3.12
py --version

macOS (Homebrew)

brew install python@3.12
python3.12 --version

Linux (Debian/Ubuntu)

sudo apt update
sudo apt install python3 python3-venv python3-pip
python3 --version

Check your version and run a first script

Confirm the install with --version. Then save the script below as hello.py and run it. The if __name__ == "__main__": guard runs main() only when the file is executed directly, a pattern every example in this course follows.

Check the version

python3 --version      # macOS / Linux
py --version           # Windows
python3 -c "print('ok')"   # run one line without a file

hello.py: first runnable script

"""First script: hello.py"""
import sys  # standard library module giving interpreter details


def main():
    # print() writes text to the terminal
    print("Hello, Python!")
    # sys.version_info tells you which Python is running this script
    v = sys.version_info
    print(f"Running Python {v.major}.{v.minor}.{v.micro}")
    # sys.executable shows which python binary is running this script
    print("Interpreter:", sys.executable)


# Runs main() only when the file is executed directly, not when imported
if __name__ == "__main__":
    main()

Run the script

python3 hello.py      # macOS / Linux
py hello.py           # Windows

Virtual environments (venv)

A virtual environment is a private folder of packages for one project, so projects never clash. Create it once with python -m venv .venv, then activate it each time you open a terminal. When active, your prompt shows (.venv) and python and pip point inside it.

Create and activate (macOS / Linux)

python3 -m venv .venv
source .venv/bin/activate
python --version
deactivate        # leave the environment

Create and activate (Windows PowerShell)

py -m venv .venv
.venv\Scripts\Activate.ps1
python --version
deactivate
# If activation is blocked:
# Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

pip and requirements.txt

pip installs packages from PyPI into the active environment. Run it as python -m pip so it matches your interpreter. Record your dependencies in requirements.txt so anyone can recreate the environment with one command.

Everyday pip commands

python -m pip install --upgrade pip
python -m pip install requests
python -m pip list
python -m pip show requests
python -m pip uninstall requests

requirements.txt workflow

python -m pip freeze > requirements.txt     # save exact versions
python -m pip install -r requirements.txt     # recreate elsewhere

# A hand-written requirements.txt can be loose:
# numpy
# pandas>=2.0
# requests

Install the libraries used later

Later modules use numpy, pandas, scikit-learn, pillow, opencv-python, torch, openai and requests. Install them inside your activated venv. torch is large (hundreds of MB to a few GB), so install it only when you reach the deep learning module. If a wheel is unavailable for your Python version, use Python 3.12.

Install everything

python -m pip install numpy pandas scikit-learn pillow opencv-python openai requests
python -m pip install torch      # large; CPU build is fine for learning

Verify the imports

python -c "import numpy, pandas, sklearn, PIL, cv2, requests, openai; print('all imports ok')"
python -c "import torch; print(torch.__version__)"

Editor tip

Use Visual Studio Code with the Microsoft Python extension. Open your project folder, press Ctrl+Shift+P (Cmd+Shift+P on macOS), choose Python: Select Interpreter and pick the one inside .venv. Then the Run button and the integrated terminal both use your project environment. You can launch the editor from a terminal with code ..

Open the project in VS Code

cd my-project
code .

Install ffmpeg

ffmpeg is a separate program (not a pip package) used for audio and video work. Install it with your system package manager and check that it is on your PATH. Python libraries then call it behind the scenes.

Windows

winget install Gyan.FFmpeg
ffmpeg -version

macOS

brew install ffmpeg
ffmpeg -version

Linux (Debian/Ubuntu)

sudo apt install ffmpeg
ffmpeg -version

API keys: environment variables, never code

Never write a key into a script, a notebook or Git. Put it in an environment variable and read it with os.environ. For a project, a .env file works with the python-dotenv package, as long as .env is listed in .gitignore. If a key is ever exposed, revoke it and create a new one.

Set a variable for this terminal session

# macOS / Linux (bash, zsh)
export OPENROUTER_API_KEY="paste-your-key-here"

# Windows PowerShell
$env:OPENROUTER_API_KEY = "paste-your-key-here"

# Windows, persistent for your user (open a new terminal afterwards)
setx OPENROUTER_API_KEY "paste-your-key-here"

Keep .env out of Git

echo ".env" >> .gitignore
echo ".venv/" >> .gitignore

Read the key safely in Python

"""Reading a secret from an environment variable, never from the source code."""
import os  # os.environ exposes environment variables


def get_api_key(name: str = "OPENROUTER_API_KEY") -> str | None:
    """Return the key if set, else None (os.environ[name] would raise KeyError)."""
    return os.environ.get(name)


def main():
    key = get_api_key()
    if key is None:
        # Never print or log a real key; just report whether it exists
        print("OPENROUTER_API_KEY is not set. Set it in your shell first.")
    else:
        print(f"Key found, {len(key)} characters long (value not shown).")
    # Provide a default for non-secret settings
    model = os.environ.get("MODEL_NAME", "example-model")
    print("Model name:", model)


if __name__ == "__main__":
    main()