In Module 5, we move from writing simple scripts to building reusable blocks of code. Functions are the “verbs” of your program—they perform specific actions and help keep your code organized and DRY (Don’t Repeat Yourself).
A function is defined using the def keyword, followed by a name and parentheses.
Example:
Python
def greet():
print("Hello, welcome to Python!")
greet() # Calling the function
Example:
Python
def greet_user(name): # 'name' is a parameter
print(f"Hello, {name}!")
greet_user("Alice") # "Alice" is an argument
The return statement sends a result back to the caller. Without a return statement, a function returns None by default.
Example:
Python
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
Example:
Python
def power(base, exponent=2): # exponent has a default value
return base ** exponent
print(power(4)) # 16 (uses default 2)
print(power(exponent=3, base=2)) # 8 (keyword arguments)
*args and **kwargsThese allow a function to accept a variable number of arguments.
*args: Collects extra positional arguments as a tuple.**kwargs: Collects extra keyword arguments as a dictionary.Example:
Python
def make_pizza(size, *toppings):
print(f"Size: {size}, Toppings: {toppings}")
make_pizza("Large", "Pepperoni", "Mushrooms", "Olives")
Lambdas are small, anonymous “one-liner” functions. They are often used for short-term tasks with functions like map() or filter().
Example:
Python
# square = lambda x: x * x
multiply = lambda a, b: a * b
print(multiply(5, 4)) # 20
Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive function needs a base case to prevent an infinite loop.
Example (Factorial):
Python
def factorial(n):
if n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
Docstrings are string literals that appear right after the function definition. They explain what the function does and are accessed via help() or .__doc__.
Example:
Python
def calculate_area(radius):
"""Calculates the area of a circle given its radius."""
return 3.14 * (radius ** 2)
print(calculate_area.__doc__)