'Can you use a variable to call a function [duplicate]

I have four subroutines to multiply, divide, add and subtract 2 numbers which I will ask the user for.

My unfinished code is:

def multiply(a, b):
    print(f"{a} x {b} = {a*b}")
    
def divide(a, b):
    print(f"{a} ÷ {b} = {a*b}")

num1 = int(input("What is the first number?\n"))
num2 = int(input("What is the second number?\n"))
calculation = input("What calculation would you like to perform? [multiply, divide]\n")

calculation(num1, num2)

but it gives TypeError: 'str' object is not callable

Is it necessary to use if statements like:

if calculation == 'multiply':
     multiply()
elif calculation == 'divide':
     divide()

for all four subroutines or can I use the variable calculation to substitute for the function name.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source