Skip to content
Home » Functions in Python – Assigning Functions to Variables

Functions in Python – Assigning Functions to Variables

Spread the love

Here’s another article in the Functions in Python series. Today we’ll be talking about assigning functions to variables. If you haven’t read the previous parts yet, feel free to do so. Here they are:

1) Introduction to Functions

2) Functions with Parameters

3) The return Statement

4) Mandatory Parameters

5) Optional Parameters

6) Mutable Optional Parameters

7) Keyword Arguments

8) Arbitrary Number of Positional Parameters

9) Arbitrary Number of Keyword Parameters

10) Arbitrary Number of Both Positional and Keyword Parameters

11) Nested Functions

12) Calling Functions in Other Functions

Functions are first-class objects, which means they are objects like any other objects, which further means they can be used just like other objects. Translating this into plain English, we can assign functions to variables and pass them as arguments to other functions. They can also be returned from other functions. If you want to read more about functions as first-class objects, I have an article about that.

Now let’s focus on assigning functions to variables. If you assign a function to a variable, you can use the variable as the function:

def double(number):
    return number * 2

print(double(5))

a = "abc"
print(a)

a = double
print(a(17))

b = a
print(b(12))

Here’s the output:

10
abc
34
24

So, in the code above the variable a was first assigned a string. Then it was assigned the double function. From this point on it’s possible to use a as the double function. Finally the variable b was assigned the same reference as a, so it also now points to the double function. In the end, we can use double, a or b and they all reference the same function.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply