🔷 Introduction
Functions are the foundation of reusable and maintainable code. At the beginner level, you learned how to define and call functions. In this lesson, we take it further by exploring advanced function features that are widely used in real-world Python applications.
You will learn:
✔ Flexible arguments with *args and **kwargs
✔ Default, positional, and keyword arguments
✔ Lambda (anonymous) functions
✔ Higher-order functions (map, filter, reduce)
✔ Introduction to decorators
These tools will allow you to write cleaner, more dynamic, and reusable code.
🟩 1. Default, Positional, and Keyword Arguments
Default arguments
def greet(name="Guest"):
print("Hello", name)
greet() # Hello Guest
greet("Ali") # Hello AliPositional vs Keyword arguments
def info(name, age):
print(name, age)
info("Sara", 25) # positional
info(age=25, name="Sara") # keyword🟩 2. args (Variable Positional Arguments)
*args allows a function to accept any number of positional arguments.
def add_numbers(*args):
total = 0
for n in args:
total += n
return total
print(add_numbers(1, 2, 3, 4)) # 10💡 args is a tuple.
🟩 3. kwargs (Variable Keyword Arguments)
**kwargs allows a function to accept any number of keyword arguments.
def display_info(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
display_info(name="Ali", age=22)💡 kwargs is a dictionary.
🟩 4. Lambda Functions (Anonymous Functions)
A lambda is a small, one-line function.
Example:
square = lambda x: x * x
print(square(5)) # 25Use with map:
nums = [1, 2, 3]
result = list(map(lambda x: x*2, nums))
print(result)🟩 5. Higher-Order Functions
These are functions that take other functions as arguments.
A. map()
Applies a function to each item:
nums = [1, 2, 3]
result = list(map(lambda x: x * 2, nums))B. filter()
Filters elements:
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums))C. reduce()
Requires functools:
from functools import reduce
nums = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, nums)🟩 6. Decorators (Introduction)
A decorator is a function that wraps another function.
Basic Example:
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapperUsing the decorator:
@my_decorator
def say_hello():
print("Hello!")
say_hello()Output:
Before function
Hello!
After function🟧 7. Exercises (Hidden Solutions)
Exercise 1 — Use args to multiply numbers
Exercise 2 — Use kwargs to print user info
Exercise 3 — Use lambda to cube numbers
Exercise 4 — Filter numbers greater than 10
Exercise 5 — Create a decorator that logs function calls
🟦 Conclusion
In this lesson, you’ve unlocked some of Python’s most powerful function features:
- Flexible argument handling
- Functional programming tools
- Anonymous functions
- Code reuse with decorators
These concepts are widely used in frameworks like Django, Flask, and FastAPI.
💬 Comments
No comments yet. Be the first to comment!
Login to comment.