5 Must-Know Secrets of Python Functions!

We all know about Python Functions but let’s go one more time. Python functions are like mini-programs inside your main program. They help you do tasks more easily and avoid repeating the same code.

Imagine you are a great Chef and one morning you got a great idea of making a Turkey Sandwich, you made it, and it tasted amazing. Instead of remembering the steps for making the sandwich every time you want one, you can just write down the recipe, refer it and follow the steps in the recipe. This way you will always have the exact same steps and you also won’t have to think much about creating the recipe again.

Functions work the same way in programming—they help you organize your code, make it easier to understand, and save you time by letting you reuse code for similar tasks. Let’s find out what are the different features of Python Functions.

Python Functions are First Class Objects

In Python, functions are first-class objects, meaning you can assign them to variables, pass them as arguments to other functions, and return them as values from other functions. This great feature allows for powerful programming method like functional programming.

I can explain this using a simple example-

def calculate(operation, x, y):
    if operation == 'add':
        return x + y
    elif operation == 'subtract':
        return x - y
    elif operation == 'multiply':
        return x * y
    elif operation == 'divide':
        return x / y

operation_func = calculate
result = operation_func('multiply', 5, 3)
print(result) 

Functions Can Be Saved in DataStructures

You can store functions in data structures like lists, dictionaries, or tuples in Python. Here’s a simple example of storing functions in a list:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x / y

calc_functions = [add, subtract, multiply, divide]

x = 10
y = 5
for func in calc_functions:
    result = func(x, y)
    print(f"Result of {func.__name__}({x}, {y}): {result}")

Functions Can Be Passed to Other Functions

Since functions are objects, you can pass them as arguments to other functions. We can understand this from below example-

def apply_operation(func, x, y):
    return func(x, y)

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

result_addition = apply_operation(add, 5, 3)
print("Result of addition:", result_addition)

result_subtraction = apply_operation(subtract, 10, 4)
print("Result of subtraction:", result_subtraction)

This allows to abstract away specific operations into separate functions that can be easily passed around and used in different contexts.
Functions that can accept other functions as arguments are also known as higher-order functions. A simple example would be ‘map’ function in Python.

Functions Can Be Nested

What are Nested Functions? Sounds like a maze, right?
You will be amazed to know that Python allows the definition of functions within other functions. These are known as nested functions or inner functions.

Let’s understand this with a simple example-

def multiplier_function(x):
    def doubler_function(y):
        return y * 2
    return doubler_function(x)

result = multiplier_function(5)
print(result)

In this example, doubler_function is the nested function. The multiplier_function multiplies its input by 2 using the doubler_function.

Functions Can Store Local State

Inner functions can not only be returned by other functions but also store and keep some of the parent function’s data. Ok, that seems weird right?
Let’s modify the earlier example and try to understand what’s happening-

def multiplier_function(x):
    def doubler_function(y):
        return y * x  
    return doubler_function

doubler_with_multiplier_3 = multiplier_function(3)

result = doubler_with_multiplier_3(5)
print(result)  # Output: 15 (5 * 3)

In this example, the doubler_function captures the value of x from the multiplier_function. When we create a doubler function with a multiplier of 3 (doubler_with_multiplier_3 = multiplier_function(3)), the x value of 3 is retained within doubler_function. So, when we call doubler_with_multiplier_3(5), it effectively doubles the number 5 by multiplying it with the captured x value of 3, resulting in 15.
I hope it all makes sense now!

Happy Learning!

Leave a comment