pythonANYfunctionsbasics
python
def greet(name: str) -> str:
return f"Hello, {name}"Functions, parameters, lambda, decorators, comprehensions, generators, and functional helpers.
Function definitions and calling conventions.
def greet(name: str) -> str:
return f"Hello, {name}"def connect(host: str, port: int = 5432) -> tuple[str, int]:
return host, portdef resize(image, *, width: int, height: int):
return image, width, heightdef total(*numbers: int) -> int:
return sum(numbers)def render(**context):
return contextcoords = (10, 20)
style = {"color": "red"}
plot(*coords, **style)rows.sort(key=lambda row: row["created_at"])Compact collection-building and lazy iteration.
squares = [n * n for n in range(10)]evens = [n for n in range(20) if n % 2 == 0]unique_lengths = {len(word) for word in words}total = sum(n * n for n in range(10))pairs = [(x, y) for x in xs for y in ys]def countdown(n: int):
while n > 0:
yield n
n -= 1Reusable wrappers and functional patterns.
@timer
def build_report():
return "done"def retry(times: int):
def decorator(fn):
def wrapper(*args, **kwargs):
for _ in range(times):
try:
return fn(*args, **kwargs)
except Exception:
pass
return fn(*args, **kwargs)
return wrapper
return decoratoruppercased = list(map(str.upper, names))valid = list(filter(None, values))from functools import reduce
product = reduce(lambda a, b: a * b, numbers, 1)from functools import partial
base2 = partial(int, base=2)
value = base2("1010")