Python Functions
Functions group reusable logic behind a name, and Python gives them unusually flexible argument handling.
Defining a function
A function is declared with the def keyword followed by a name and a parameter list.
def greet(name, greeting="Hello"):
"""Return a greeting for the given name."""
return f"{greeting}, {name}!"
print(greet("Ada"))
print(greet("Ada", greeting="Welcome"))Argument types
- Positional arguments are matched by order.
- Keyword arguments are matched by name.
- Default arguments supply a fallback value.
- *args collects extra positional arguments into a tuple.
- **kwargs collects extra keyword arguments into a dictionary.
def summarise(*values, **options):
total = sum(values)
label = options.get("label", "Total")
return f"{label}: {total}"
print(summarise(1, 2, 3, label="Score"))Scope
Names assigned inside a function are local unless declared global or nonlocal. Python resolves names using the LEGB rule: Local, Enclosing, Global, Built-in.
Lambda functions
squares = list(map(lambda x: x * x, range(6)))
print(squares)Conclusion
Keep functions short, give them one clear responsibility and return values rather than printing them, so they stay testable.