top of page

Passing functions as arguments to other functions..

Updated: Jun 6

Python has more surprises than you think!

As someone who has been teaching Python for many years, I’ve noticed that even seasoned programmers often overlook certain powerful features of the language. These hidden gems can make your code more elegant and efficient.


Higher-Order Functions (Functions Accepting Other Functions)

You can create a function that takes another function as an argument and applies it to some data.

Functions are fun

Real-life example: Applying Different Discount Strategies

Let’s say you’re working with an e-commerce app where you need to apply different discount strategies to a cart total. You can pass the discount functions as arguments to a main function that calculates the final price.


def apply_discount(price, discount_func): //accepts function as a param
    return discount_func(price)
def ten_percent_discount(price):
    return price * 0.9
def fixed_discount(price):
    return price - 50
total_price = 200
final_price = apply_discount(total_price, ten_percent_discount)
print(f"Price after 10% discount: {final_price}")  # Output: 180.0
final_price = apply_discount(total_price, fixed_discount)
print(f"Price after $50 discount: {final_price}")  # Output: 150.0

A bit Advanced - Passing Lambda Functions

You can also pass lambda functions, which are small anonymous functions, for quick and temporary operations.

# Use a lambda function for a custom discount
final_price = apply_discount(total_price, lambda price: price * 0.8)
print(f"Price after custom 20% discount: {final_price}")  # Output: 160.0

FREE PYTHON MASTERCLASS - 4 HOURS (WEEKEND)
Python Masterclass (4 hours)
14 September 2024, 12:00 – 4:00 pmFree Webinar
Register Now

Why It’s Exciting:

  • Flexibility: You can change the behavior of functions dynamically by passing different functions as arguments.

  • Cleaner code: This removes the need for many if/else blocks, as different behaviors can be achieved by passing different functions.

  • Reusability: The main function (apply_discount) becomes highly reusable with different discount strategies.


Curious to discover more hidden Python features? Comment below and let’s dive into the lesser-known corners of this versatile language!



IS PYTHON YOU FIRST CHOICE TO LEARN?

  • YES

  • NO

  • MATLAB, AISA IMMEDIATE SOCHA NAHI HAI


Comments


bottom of page