How to Use a Variable as Function Name in Python

In Python, We can use variables to replace the function names and call the function. In the below example, function names are stored as a list, with a for loop we are looping the function names from the list and calling using a variable

Now, the Variable will be replaced with the function name -> Here i() will be replaced a() and it will start to execute the function a()

Example:

def a():
	print("a")

def b():
	print("b")

def c():
	print("c")
	
list = [a,b,c]

for i in list:
	i()

Try it Yourself

Continue reading, If you like to see, How it is getting used in real-time projects and the mistake I did while using this.

Check the below Calculator program snippet and will discuss more it below

def add(n1, n2):
  return n1 + n2

def subtract(n1, n2):
  return n1 - n2

def multiply(n1, n2):
  return n1 * n2

def divide(n1, n2):
  return n1 / n2

operations = {
  "+": add,
  "-": subtract,
  "*": multiply,
  "/": divide
}
num1 = float(input("What's the first number?: "))
for symbol in operations:
  print(symbol)
operation_symbol = input("Pick an operation: ")
num2 = float(input("What's the next number?: "))
calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)
print(answer)

Try it Yourself

  • In this example, We have created functions (addition, subtraction, multiplication, division)
  • These operator and function name has been stored as key: value (“+”: add)
  • Each time user picks an operator lie (+,-,*,/), I will use the operator as a key and fetch the value (function name)

Now, Let’s consider, I am picking the “+” addition operator, this will fetch the “add” function name which will be replaced below

1.

calculation_function = operations[+]

2.

calculation_function = add

3.

answer = add(num1, num2)

After all substitutions, your add function will be called and you will have the output saved in the “answer” variable, Later it can be printed to the users as below

 print(f"{num1} {operation_symbol} {num2} = {answer}")

While creating this program, I made a mistake and was so difficult to find what went wrong.

I got the error “TypeError: ‘str’ object is not callable error” while running the above code snippet. That is because

In the dictionary, I saved the function name as “string” and it didn’t work as expected

operations = {
  "+": “add”,
  "-": “subtract”,
  "*": “multiply”,
  "/": “divide”
}

and If you run the below code with the above dictionary:

 answer = calculation_function(num1, num2)

You will see an error “TypeError: ‘str’ object is not callable error”

This is because, the function name is refereed as an object and you can directly save the function name as an object, Instead, If you save the function name as a string it will give the above error as it is unable to call the string in the place of the function name

Example: “add”(num1,num2)

Click here to know more about dictionary with example program

Click here to see other article related to python learning series

Good Luck with your learning, Initiate a discussion if you have any questions or any other alternative method in achieving the above logic.

Similar Posts