A function packages up logic so it can be reused by name — the same idea from Intro to Programming, defined in Python with the def keyword.
def greet(name):
return f"Hello, {name}!"
print(greet("Priya")) # "Hello, Priya!"def greet(name="Guest"):
return f"Hello, {name}!"
print(greet()) # "Hello, Guest!"
print(greet("Amit")) # "Hello, Amit!"Python lets you optionally annotate parameter and return types — unlike PHP's type declarations, these are not enforced at runtime; they're documentation and tooling support (your editor can catch a mismatch), not a hard rule the way PHP's function add(int $a, int $b): int is:
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3)) # 5
print(add("2", "3")) # "23" — no error! type hints don't stop this at runtimeA Python function can return more than one value directly, separated by commas — under the hood, this is really returning a tuple (from the Tuples and Sets lesson):
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([4, 9, 1, 7])
print(low, high) # 1 9These let a function accept any number of arguments — *args collects extra positional arguments into a tuple, **kwargs collects extra named arguments into a dict:
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total(1, 2, 3, 4, 5)) # 15 — works with any number of arguments
def describe(**details):
for key, value in details.items():
print(f"{key}: {value}")
describe(name="Priya", course="Web Development")