Assign Function to a Variable in Python
🔍 What Does “Assign Function to a Variable” Mean?
In Python, functions are treated as first-class objects. This means you can:
- Assign a function to a variable
- Pass a function as an argument
- Return a function from another function
👉 Simply put, you can store a function inside a variable and use it later.
✨ Why Assign Functions to Variables?
- ✅ Makes code flexible
- ✅ Helps in functional programming
- ✅ Reduces code duplication
- ✅ Useful for callbacks and dynamic behavior
🧠 Basic Syntax
variable_name = function_name
📌 Simple Example
def greet():
return "Hello, Python!"
# Assign function to a variable
say_hello = greet
print(say_hello())
👉 Output:
Hello, Python!
🔢 Example with Parameters
def add(a, b):
return a + b
# Assign function
sum_func = add
print(sum_func(10, 5))
👉 Output:
15
🔄 Functions as First-Class Objects
In Python, functions behave like other data types:
✔ Store in Variables
func = print
func("Hello World")
✔ Pass as Argument
def operate(func, x, y):
return func(x, y)
def multiply(a, b):
return a * b
print(operate(multiply, 4, 5))
✔ Return from Another Function
def outer():
def inner():
return "Inside Function"
return inner
my_func = outer()
print(my_func())
🔁 Lambda Function Assignment
square = lambda x: x * x
print(square(6))
👉 Output:
36
⚠️ Important Note
👉 When assigning a function to a variable, do NOT use parentheses:
❌ Wrong:
func = greet()
✔ Correct:
func = greet
📦 Advantages
- ✔ Supports functional programming
- ✔ Cleaner and shorter code
- ✔ Dynamic function usage
- ✔ Improves code reusability
🚀 Real-World Use Case
def logger(message):
print("Log:", message)
def executor(func):
func("Task executed")
executor(logger)
📝 Conclusion
Assigning functions to variables in Python is a powerful feature that makes your code more flexible and dynamic. It is widely used in advanced topics like decorators, callbacks, and higher-order functions.
🔑 Keywords
Assign function to variable in Python, Python first class functions, Python function assignment examples, Python functional programming, Python lambda functions, Python coding tutorial
0 Comments