Assign Function to a Variable in Python

Assign Function to a Variable in Python

In Python, functions are first-class objects. This means that, just like any other object (e.g., string, int, list), a function can be assigned to a variable, passed as an argument to another function, or returned as a value from a function.

Here's how you can assign a function to a variable:

  • Basic example:
def greet(): return "Hello, world!" # Assign function to a variable say_hello = greet # Call the function through the variable print(say_hello()) # Output: Hello, world! 

Note that when assigning the function to a variable, you don't include the parentheses (). Including the parentheses would call the function, and the return value of the function would be assigned to the variable, not the function itself.

  • Passing a function as an argument:

Functions can also be passed as arguments to other functions:

def add(a, b): return a + b def subtract(a, b): return a - b def calculate(func, a, b): return func(a, b) result1 = calculate(add, 5, 3) # Output: 8 result2 = calculate(subtract, 5, 3) # Output: 2 print(result1, result2) 
  • Returning a function from another function:

You can also return a function from another function:

def get_operation(operation): def add(a, b): return a + b def subtract(a, b): return a - b if operation == "add": return add else: return subtract operation = get_operation("add") print(operation(5, 3)) # Output: 8 

These concepts are foundational for understanding more advanced topics in Python like decorators and closures.


More Tags

capl git-rewrite-history quantmod kaggle array-map primeng-dropdowns postgresql 64-bit readonly pseudo-class

More Programming Guides

Other Guides

More Programming Examples