Python supports functional programming in addition to imperative paradigms. In the previous sections, we have seen some functional programming constructs without an explicit explanation. Let's go over them in this section. Functions are first-class citizens in Python. They have attributes and they can be referenced and assigned to a variable.
Let's look at the paradigm of passing a function as a variable in Python in this section.
Let's define a simple function and see how it can be used as a variable:
# 1.Let us define a simple function. def square_input(x): return x*x # We will follow it by assigning that function to a variable square_me = square_input # And finally invoke the variable print square_me(5)
We defined a simple function in step 1; with an input, the function returns the square of the input. We assigned this function to a square_me
variable. Finally, we were able to invoke the function by calling square_me
with a valid parameter. This demonstrates how a function can be treated as a variable in Python. This is a very import functional programming construct.