Variables
x: int = 5
name: str = "drone"
battery: float = 100.0
active: bool = True
capabilities: list[str]
CAPABILITIES: dict[int , list[str]] # dict mapping
# union — either type
def foo(x: str | None) -> None: ...
# set of (int, int) tuples
_blocked: set[tuple[int, int]]
# callable — a function that takes Drone+int, returns Awaitable[None]
on_waypoint: Callable[[Drone, int], Awaitable[None]] | None
- The
: int is a type hint
- Not enforce it at runtime
- linter, IDE can use it to catch mistakes early
Lists, Dicts, Sets
# list : ordered, allows duplicates
capabilities = ["thermal_scan", "move_to"]
capabilities.append("deliver_aid") # add to end
capabilities[0] # "thermal_scan"
# dict : key → value
position = {"x": 3, "y": 2, "z": 0}
position["x"] # 3
position.get("w", 0) # 0 (default if key missing)
# set : unordered, no duplicates, fast lookup
blocked = {(3, 2), (4, 5)}
(3, 2) in blocked # True — O(1), much faster than list
blocked.add((7, 1))
blocked.discard((3, 2)) # remove if exists, no error if not
Function
def add(a: int, b: int) -> int:
return a + b
# default parameter
def move(x: int, y: int, z: int = 0) -> None:
...
# ... means "nothing here yet"
if / elif / else
if drone.battery <= 5.0:
print("critical")
elif drone.battery <= 20.0:
print("low")
else:
print("ok")
for loops
# loop over a list
for cap in capabilities:
print(cap)
# loop over a range
for i in range(3): # 0, 1, 2
print(i)
# nested — used in thermal_scan
for dy in range(-3, 4): # -3, -2, -1, 0, 1, 2, 3
for dx in range(-3, 4):
nx, ny = drone.x + dx, drone.y + dy
try / except