Python - Running Code

Overview

Estimated time: 20–30 minutes

Run Python interactively in the REPL, execute scripts from files, use shebangs, and structure scripts with the main guard pattern.

Learning Objectives

  • Start and use the Python REPL for quick experiments.
  • Run .py files from the command line and pass arguments.
  • Use the main guard (if __name__ == \"__main__\":) to separate importable code from script entry points.

Prerequisites

Interactive REPL

python  # or: python3
>>> 2 + 3
5
>>> print("Hello")
Hello
>>> exit()

Run scripts

python app.py
python app.py --name Alice

Main guard

def greet(name: str) -> None:
    print(f"Hello, {name}!")

if __name__ == "__main__":
    greet("World")

Expected Output:

Hello, World!

Common Pitfalls

  • Forgetting the main guard, causing code to run on import.
  • Using the wrong Python executable (system vs venv). Always activate your venv first.

Checks for Understanding

  1. Why is the main guard useful in Python scripts?
  2. How do you exit the REPL?
Show answers
  1. It prevents script-only code from running when the module is imported.
  2. Type exit() or press Ctrl-D (Unix) / Ctrl-Z then Enter (Windows).

Exercises

  1. Create a script that prints the sum of two numbers given as CLI arguments.
  2. Refactor your code to put logic in functions and call them from within the main guard.