简体   繁体   中英

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)
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM