Functions & Lambdas
Functions are a way to bundle a set of instructions that you want to use repeatedly. They make your code modular, readable, and easier to debug.
1. Defining a Function
Use the def keyword followed by the function name and parentheses.
def greet(name):
return f"Hello, {name}!"
message = greet("Pradeep")
print(message)
2. Dynamic Arguments
- Default Arguments: Provide a fallback value.
- *args: Receive a variable number of positional arguments (as a tuple).
- **kwargs: Receive a variable number of keyword arguments (as a dictionary).
def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3, 4)) # 10
3. Lambda Expressions
Lambdas are small, anonymous functions that can have any number of arguments but only one expression. They are often used with map() and filter().
# Standard: sum = lambda a, b : a + b
square = lambda x : x * x
print(square(5)) # 25
# Used in sorting
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
pairs.sort(key=lambda pair: pair[1])
Docstrings: Professional functions always include a "docstring" triple-quoted at the top to explain what the function does.