description: "Setup & First Program — if name == 'main': guards code so it only runs when the file is executed directly, not when it's imported by another…"---
01 · Setup & First Program¶
Install Python¶
Download Python 3.12+ from python.org or use your OS package manager:
# macOS (Homebrew)
brew install python
# Ubuntu/Debian
sudo apt install python3 python3-venv
# Windows: use the installer from python.org and check "Add to PATH"
Verify the install:
The REPL¶
The REPL (Read-Eval-Print Loop) is an interactive Python shell — great for quick experiments:
Your first script¶
Create hello.py:
# hello.py
def greet(name: str) -> str:
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("world"))
Run it:
if __name__ == "__main__": guards code so it only runs when the file is executed
directly, not when it's imported by another module (covered in Module 9).
Choosing an editor¶
Any of these work well for this program: VS Code (free, huge Python extension ecosystem), PyCharm Community (free, Python-specific), or even a plain text editor plus the terminal. Pick one and move on — the editor matters far less than practice.
How It Actually Works¶
When you type python3 hello.py, a lot happens before "Hello, world!" appears:
- Interpreter startup. The OS loads the
python3executable, which initializes the CPython runtime: it sets up the interpreter state, buildssys.path(from the executable's location,PYTHONPATH, and compiled-in defaults), and imports a handful of bootstrap modules written in C and frozen into the binary. - Reading and compiling your file. CPython reads
hello.pyas text, tokenizes it, parses the tokens into an Abstract Syntax Tree, and compiles that AST into bytecode — a compact instruction set for CPython's virtual machine. Yourdef greetbecomes a code object holding those instructions plus metadata (argument names, constants, line numbers). .pyccaching. For imported modules CPython writes the compiled bytecode to__pycache__/*.pycso it can skip recompilation next time, keyed by the source file's hash or mtime. The top-level script you run directly is not cached this way.- Execution. CPython creates a module object, sets its
__name__to"__main__"(this is the whole reason theif __name__ == "__main__"guard works), and runs the module's bytecode top to bottom in the evaluation loop — a big Cswitchover bytecode instructions.def greetexecutes as a "make a function object and bind the namegreet" instruction; theifblock then calls it. - Shutdown. After the last instruction, CPython runs cleanup (flushing
stdout, runningatexithandlers, garbage-collecting), then the process exits with status code 0.
The REPL runs this same read → compile → execute loop, but once per line you type instead of once per file.
🔀 See this in another language¶
Exercise¶
Write a script greet_many.py that defines a list of three names and prints a
greeting for each one using the greet function above.