Python Advance Course
First-Class Functions in Python
First-Class Functions in Python
In Python, functions are first-class citizens, meaning functions can be treated like any other object (int, string, list, etc.).
This means you can: - Assign functions to variables - Pass functions as arguments - Return functions from other functions - Store functions inside data structures
1. Assigning Functions to Variables
A function can be assigned to a variable and used through that variable.
Example:
def greet():
return "Hello"
say_hello = greet
print(say_hello())
Output:
Hello
Real-world example: A payment system where different payment methods are assigned dynamically.
def pay_by_card():
return "Paid using Card"
def pay_by_upi():
return "Paid using UPI"
payment = pay_by_upi
print(payment())
Output:
Paid using UPI
Common Mistake
def greet():
return "Hello"
g = greet()
print(g())
Error:
- Because greet() is executed immediately instead of assigning function
Correct:
g = greet
Homework 1
Create a function add() and assign it to a variable operation. Call it using the variable.
Solution:
def add():
return 5 + 3
operation = add
print(operation())
2. Passing Functions as Arguments
Functions can be passed into other functions.
Example:
def add(a, b):
return a + b
def calculate(func, a, b):
return func(a, b)
print(calculate(add, 10, 5))
Output:
15
Real-world example: Different discount strategies in e-commerce.
def discount_10(price):
return price * 0.9
def discount_20(price):
return price * 0.8
def apply_discount(func, price):
return func(price)
print(apply_discount(discount_10, 1000))
Output:
900.0
Common Mistake
def add(a, b):
return a + b
print(calculate(add(), 10, 5))
Problem:
- add() is called instead of passing function reference
Correct:
calculate(add, 10, 5)
Homework 2
Create: - multiply function - pass it into a calculator function
Solution:
def multiply(a, b):
return a * b
def calculator(func, a, b):
return func(a, b)
print(calculator(multiply, 4, 5))
3. Returning Functions
A function can return another function.
Example:
def outer():
def inner():
return "Inner function called"
return inner
f = outer()
print(f())
Output:
Inner function called
Real-world example: Login system based on user roles.
def role_checker(role):
def admin():
return "Admin Access"
def user():
return "User Access"
if role == "admin":
return admin
else:
return user
access = role_checker("admin")
print(access())
Output:
Admin Access
Common Mistake
def outer():
def inner():
return "Hello"
return inner()
f = outer
print(f())
Issues: - Function not called correctly
Correct:
f = outer()
Homework 3
Create a function that returns a function which multiplies by 2.
Solution:
def outer():
def inner(x):
return x * 2
return inner
double = outer()
print(double(10))
4. Storing Functions in Data Structures
Functions can be stored in lists, dictionaries, etc.
Example (List):
def add(a, b):
return a + b
def sub(a, b):
return a - b
operations = [add, sub]
print(operations[0](10, 5))
print(operations[1](10, 5))
Output:
15
5
Example (Dictionary - Real World Use Case):
def deposit():
return "Money Deposited"
def withdraw():
return "Money Withdrawn"
bank_ops = {
"d": deposit,
"w": withdraw
}
print(bank_ops["d"]())
Output:
Money Deposited
Real World Analogy
| Concept | Real World Example |
|---|---|
| Function variable | Remote control button mapped to TV action |
| Passing function | Choosing payment method |
| Returning function | Role-based access system |
| Function storage | Menu system in ATM |
Graph (Conceptual Flow)
Function Object
|
+--> Assigned to variable
+--> Passed as argument
+--> Returned from function
+--> Stored in list/dict
Common Mistakes Summary
| Mistake | Problem |
|---|---|
| add() instead of add | function executed instead of passed |
| returning func() instead of func | returns result instead of function |
| calling function too early | breaks higher-order logic |
Homework 4 (Mixed Challenge)
Create a calculator system: - add, subtract, multiply functions - store them in dictionary - take input key and execute function
Solution:
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
ops = {
"+": add,
"-": sub,
"*": mul
}
print(ops["+"](10, 5))
Next Advanced Topics to Learn
- Closures in Python
- Decorators
- Lambda Functions
- Higher Order Functions in depth
- Functional Programming in Python
- functools module (map, filter, reduce) ```