Enter mathematical operators using input tag
I am using the following code for Addition, Subtraction, Multiplication, and Division. Users will be entering the operator of their own choice. Is there a simple way to get the input from a user and display the result, instead of writing if op=='+':
?
num1 = int(input("Enter first number"))
num2 = int(input("Enter second number"))
op = input("Enter mathematical operator")
if op == '+':
print("Result is ", num1+num2)
if op == '-':
print("Result is ", num1-num2)
if op == '*':
print("Result is ", num1*num2)
if op == '/':
print("Result is ", num1/num2)
if op == '%':
print("Result is ", num1%num2)
if op == '**'
print("Result is ", num1**num2)
if op == '//':
print("Result is ", num1//num2)
Solution 1:
num1 = int(input("Enter first number"))
num2 = int(input("Enter second number"))
op = input("Enter mathematical operator")
if op in ('+', '-', '*', '/' , '//', '%', '**'):
print("Result is", eval(f"{num1}{op}{num2}"))
else:
print("Operator not recognized.")
eval
is a dangerous function, because it can execute arbitrary Python code, but in this case I'm filtering the input so I know the expression is legitimate.