InPython,functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability.
Example:
Python# defining a functiondefa():print("GFG")# assigning function to a variablevar=a# calling the variablevar()
Explanation: a()prints "GFG". It is assigned tovar, which now holds a reference toa(). Callingvar()executesa().
Implementation:
To assign a function to a variable, use the function name without parentheses (). If parentheses are used, the function executes immediately and assigns its return value to the variable instead of the function itself.
Syntax:
# Defining a function
def fun():
# Function body
pass
# Assigning function to a variable
var = fun
# Calling the function using the variable
var()
Example 1: Function with Local and Global Variables
Pythonx=123# global variabledefdisplay():x=98# local variableprint(x)print(globals()['x'])# accesses global xprint(x)a=display# assign function to a variablea()# call functiona()# call function
Explanation: Insidedisplay(), localx = 98 is printed first, then globalx= 123 usingglobals()['x']. The function is assigned toa, allowingdisplay() to run twice viaa().
Example 2:Assigning a Function with Parameters
Python# defining a functiondeffun(num):ifnum%2==0:print("Even number")else:print("Odd number")# assigning function to a variablea=fun# calling function using the variablea(67)a(10)a(7)
OutputOdd numberEven numberOdd number
Explanation: fun(num) checks if num is even or odd and prints the result. It is assigned toa, allowing it to be called usinga(num), which executes fun(num).
Example 3:Assigning a Function that Returns a Value
Python# defining a functiondeffun(num):returnnum*40# assigning function to a variablea=fun# calling function using the variableprint(a(6))print(a(10))print(a(100))
Explanation: function fun(num) returns num * 40. It is assigned toa, allowing a(num)to executefun(num).