Python Basics
10 examples to get you started with Python fundamentals - 7 basic and 3 intermediate.
Prerequisites
- Python 3.14.0 installed (
python3 --version). - Optional: create an isolated environment with
uv venvorpython -m venv .venvbefore installing packages.
Basic Examples
1. Hello and the REPL
Run Python interactively or as a script.
# hello.py
def main() -> None:
name = "world"
print(f"Hello, {name}!")
if __name__ == "__main__":
main()python3 hello.pyruns the script;python3alone opens the REPL.if __name__ == "__main__"guards code that should run only when executed directly.- Use the REPL to probe APIs before writing a full module.
2. Variables and Dynamic Typing
Names refer to objects; types live on objects, not names.
count = 10 # int
count = "ten" # now str - legal in Python
items: list[int] = [1, 2, 3] # optional type hint; runtime still dynamic- Assignment binds a name to an object - it does not declare a fixed type.
- Type hints are for static checkers (mypy, pyright), not runtime enforcement.
istests object identity;==tests value equality.
Related: Variables, Types & Dynamic Typing - reference semantics
3. Numbers and Booleans
Integers are arbitrary precision; floats follow IEEE 754.
big = 10**100
ratio = 1 / 3
truthy = bool("non-empty") # True
falsy = bool("") # False//is floor division;/always returns float in Python 3.DecimalandFractionavoid float surprises for money and ratios.- Non-zero numbers and non-empty containers are truthy in
ifconditions.
Related: Numbers, Booleans & Arithmetic - Decimal and float gotchas
4. Strings and f-strings
Format text with readable inline expressions.
user = "Ada"
score = 98.5
msg = f"{user} scored {score:.1f}%"
escaped = r"C:\new\path" # raw string - backslashes literal- f-strings evaluate at runtime and support format specs (
:.2f,:,). stris Unicode text;bytesis raw binary - decode explicitly with an encoding.- Triple-quoted strings preserve newlines for docstrings and SQL.
Related: Strings & f-strings - Unicode and bytes
5. Control Flow with if and for
Branch and loop with Python's indentation-based blocks.
values = [1, 2, 3, 4]
evens = []
for n in values:
if n % 2 == 0:
evens.append(n)
else:
print("loop finished") # runs when loop completes without break- Indentation (4 spaces typical) defines block scope - no braces.
foriterates any iterable, not just lists.elseon aforloop runs only if the loop did notbreak.
Related: Control Flow - match/case and while
6. match / case (Structural Pattern Matching)
Match on shape, not just value (Python 3.10+).
def describe(value: object) -> str:
match value:
case int(n) if n < 0:
return "negative int"
case int(n):
return f"int {n}"
case [first, *rest]:
return f"list starting with {first}"
case {"id": int(uid), "name": str(name)}:
return f"user {uid}: {name}"
case _:
return "something else"- Patterns can destructure lists, dicts, and objects.
case _is the wildcard fallback.- Prefer
matchwhen branching on structure; useif/eliffor simple booleans.
Related: Control Flow - full match guide
7. List Comprehension
Build lists declaratively in one expression.
squares = [n * n for n in range(10) if n % 2]
mapping = {name: len(name) for name in ["ada", "linus", "guido"]}
unique_lengths = {len(name) for name in ["ada", "linus"]}- Comprehensions are often faster and clearer than manual
appendloops. - Dict and set comprehensions use
{key: val}and{item}syntax respectively. - Use a generator expression
(x for x in items)when you only need lazy iteration.
Related: Comprehensions & Generator Expressions - when to prefer generators
Intermediate Examples
8. Functions with Flexible Arguments
Accept positional, keyword, and variadic parameters.
def connect(host: str, port: int = 443, **options: object) -> dict:
return {"host": host, "port": port, **options}
def total(*amounts: float, tax: float = 0.0) -> float:
return sum(amounts) * (1 + tax)
connect("api.example.com", timeout=5, verify=True)
total(10.0, 20.0, tax=0.08)- Parameters after
*are keyword-only (taxintotal). **optionscollects extra keyword arguments into a dict.- Default mutable arguments (
=[]) are a common bug - useNoneand assign inside.
Related: Functions, Args & Scope - LEGB scope rules
9. Modules and Imports
Organize code into reusable modules and packages.
# In myapp/utils.py
def slugify(text: str) -> str:
return text.lower().replace(" ", "-")
# In myapp/main.py
from myapp.utils import slugify
print(slugify("Hello World"))- Each
.pyfile is a module; folders with__init__.py(or namespace packages) form packages. - Prefer absolute imports (
from myapp.utils import ...) in application code. - Run as a module with
python -m myapp.mainso imports resolve correctly.
Related: Modules, Imports & Packages - avoiding circular imports
10. Files with pathlib and Context Managers
Read and write files safely with automatic cleanup.
from pathlib import Path
config_path = Path("config.json")
config_path.write_text('{"debug": true}', encoding="utf-8")
data = config_path.read_text(encoding="utf-8")
with Path("log.txt").open("a", encoding="utf-8") as fh:
fh.write("started\n")pathlib.Pathwraps OS paths with a consistent API.- Always pass
encoding="utf-8"for text files on all platforms. withensures files close even when an exception occurs.
Related: Files & I/O - binary I/O and encodings
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.