Python Basics
10 examples to get you started with Python fundamentals - 7 basic and 3 intermediate.
Search across all documentation pages
10 examples to get you started with Python fundamentals - 7 basic and 3 intermediate.
python3 --version).uv venv or python -m venv .venv before installing packages.Run Python interactively or as a script.
# hello.py
def main() -> None:
name = "world"
print(f"Hello, {name}!")
if __name__ == "__main__":
main()python3 hello.py runs the script; python3 alone opens the REPL.if __name__ == "__main__" guards code that should run only when executed directly.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 dynamicis tests object identity; == tests value equality.Related: Variables, Types & Dynamic Typing - reference semantics
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.Decimal and Fraction avoid float surprises for money and ratios.if conditions.Related: Numbers, Booleans & Arithmetic - Decimal and float gotchas
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:.2f, :,).str is Unicode text; bytes is raw binary - decode explicitly with an encoding.Related: Strings & f-strings - Unicode and bytes
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 breakfor iterates any iterable, not just lists.else on a for loop runs only if the loop did not break.Related: Control Flow - match/case and while
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"case _ is the wildcard fallback.match when branching on structure; use if/elif for simple booleans.Related: Control Flow - full match guide
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"]}append loops.{key: val} and {item} syntax respectively.(x for x in items) when you only need lazy iteration.Related: Comprehensions & Generator Expressions - when to prefer generators
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)* are keyword-only (tax in total).**options collects extra keyword arguments into a dict.=[]) are a common bug - use None and assign inside.Related: Functions, Args & Scope - LEGB scope rules
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")).py file is a module; folders with __init__.py (or namespace packages) form packages.from myapp.utils import ...) in application code.python -m myapp.main so imports resolve correctly.Related: Modules, Imports & Packages - avoiding circular imports
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.Path wraps OS paths with a consistent API.encoding="utf-8" for text files on all platforms.with ensures 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+.
Reviewed by Chris St. John·Last updated Jul 16, 2026