Functions - 22-10-2024
Functions - 22-10-2024
D.HEMILA REXLINE
SCOPE
Function Composition in Python
Function composition combines two functions in such a way that the result of one function is passed as an
argument to the other function. It can be denoted as f(g(x)) where, x is an argument to the function g() and
the result of g(x) is an argument to the function f(). The result of function composition is finally given as the
result of function f().
def add(x, value):
return x + value
Example:
def multiply(x, factor):
return x * factor
#Syntax def compose(f, g):
def compose(f, g): def composed_function(x, value, factor):
def composed_function(x): return f(g(x, value), factor)
return f(g(x)) return composed_function
return composed_function # Create a composed function
composed_func = compose(multiply, add)
Example
def add_numbers(a, b):
"""
Adds two numbers together.
Parameters:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The sum of a and b.
Example:
>>> add_numbers(2, 3)
5
"""
return a + b
Returns:
int: The factorial of n.
"""
if n == 1 or n == 0: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive case
# Example usage:
result = factorial(5)
print(factorial.__doc__)
print("Factorial of 5 is:", result)
•Base case: If n is 0 or 1, return 1 (since 0!=1!=1).
•Recursive case: Multiply n by the factorial of n−1. The recursion continues
until the base case is reached.
Advantages of Recursive Functions: