Control flow and functions
if / elif / else
def grade(score: int) -> str:
if score >= 90:
return "A"
elif score >= 80:
return "B"
else:
return "C"
Loops
for iterates over any iterable (list, string, range, …):
for i in range(3):
print(i)
items = ["a", "b", "c"]
for item in items:
print(item)
while repeats while a condition is true.
Functions
Define with def, document with a docstring, optionally annotate parameters and return type:
def add(a: int, b: int) -> int:
"""Return the sum of a and b."""
return a + b
Multiple return values use a tuple (often unpacked):
def divmod_custom(a: int, b: int) -> tuple[int, int]:
return a // b, a % b
q, r = divmod_custom(10, 3)
Implement
- Write
clamp(value: int, low: int, high: int) -> intthat returnsvaluelimited to[low, high]. - Write a loop that prints squares for
ifrom 0 through 5 (e.g.i * i). - Commit and push.