Functions are one of the most essential features of python programming. They allow you to organize your code, make it reusable and create more modular programs. In this blog, we will explore different types of functions you can create in python and when to use them.
- Regular Function: Is a basic function that accepts parameters and returns a value. It is the most used function in python. You can use this function when you need to perform a straightforward operation such manipulating data.
def function_name(name): print(f"Hello, {name}!") function_name("Sam")
- Lambda Function: lambda functions are short, anonymous functions defined using the lambda keyword. Useful for short one-line operations. Often in combination with higher order functions like map() or filter().
square = lambda x: x+12 square(2)
- Recursive Function: A recursive function is one that calls itself. Often used to solve problems that can be broken down into smaller, similar sub-problems, such as factorials, Fibonacci sequences and tree traversals.
def factorial(n): if n==0: return 1 else: return n*factorial(n-1) factorial(5)
- Function with variable number of arguments: Python allows functions to accept a variable number of arguments using *args(for non-keyword arguments) and **kwargs(for keyword arguments). This allows you to pass any number of values to the function. Use variable arguments when you are unsure of how many arguments the function might need to handle or when you want to make the function more flexible.
def non_key_fun(*args): output = sum([arg for arg in args]) return output non_key_fun(1,2,3,4)
def key_fun(**kwargs): for k,v in kwargs.items(): print(f"{k} = {v}") key_fun(name="Sam", age=31)
- Higher order function: A higher order function is a function that takes another function as an argument or returns a function. higher order function is useful for creating more abstract or reusable behavior.
def high_order_fun(f,value): return f(value) f = lambda x:x*2 high_order_fun(f,9)
- Generator function: Generator functions use the yield keywords to return an iterator. Are useful when dealing with larger datasets or when you want to save memory by yielding results one at a time instead of generating all results at once.
def generator_fun(): yield 1 yield 3 yield 5 for i in generator_fun(): print(i)
- Decorator function: Takes another function as an argument, modifies or enhances its behavior and returns a new function. Used especially for logging, access control, memorization and more.
def decorator_fun(func): def wrapper(): print("befor function") func() print("after function") return wrapper @decorator_fun def new_fun(): print("Hello!") new_fun()