'''
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
CodePudding user response:
If Someone Wonders The Answer Ive Been Able To Figure That Out
eval(operator "()")
Adding this function willl fix it ;)
CodePudding user response:
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()}')