Scope, Docstrings, and Type Hints
Scenario: A teammate needs to know what a function expects without reading its body.
New words, in plain English
- Scope - where a name can be used
- Local variable - a name created inside a function
- Docstring - the first string documenting a function
- Type hint - optional documentation about expected types
Python resolves names through local, enclosing, global, then built-in scopes. Avoid mutable global state. Docstrings feed help; annotations help editors and type checkers but Python does not enforce them automatically.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
def port_label(port: int) -> str:
"""Return a display label for a TCP port."""
return f"tcp/{port}"
Tip: A short function with a precise name and return value often needs fewer comments.
Goal: Practice this idea in the py-first-function challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.