'How Can I Call A Function With Variable Value in python

'''

operator = input("Enter What You Wanna Do (add/sub/multi/div")
firstNum = int(input("Enter First Number:"))
secondNum = int(input("Enter Second Number:"))

def add(result):
    result = firstNum + secondNum
    return result
def sub(result):
    result = firstNum - secondNum
def multi(result):
    result = firstNum * secondNum
    return result
def div(resukt):
    result = firstNum / secondNum
    return result

'''

in this code how can i call all those functions when needed without 4 if statements i tried to add like operator() in hopes of it will take value of operator variable and call specific user entered function but it failed can some one give an option



Solution 1:[1]

If Someone Wonders The Answer Ive Been Able To Figure That Out

eval(operator+"()")

Adding this function willl fix it ;)

Solution 2:[2]

To answer the question in the title you can use globals() to return a function based on a string. Here, that would look something like:

operator = input("Enter What You Wanna Do (add/sub/multi/div)")
firstNum = int(input("Enter First Number:"))
secondNum = int(input("Enter Second Number:"))

def add():
    result = firstNum + secondNum
    return result

func_obj = globals()[operator]
print(f'The answer is {func_obj()}')

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Isath Nenuka
Solution 2 BTables