我想将这个原始代码更改为我的想法,
num1 = float(input('enter your first number :'))
op = input('choose your operator: ')
num2 = float(input('enter your second number :'))
if op == '-':
print(num1 - num2)
elif op == '+':
print(num1 + num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(num1 / num2)
else:
print('invalid operator')
并更改为这样。 但它只显示第一个操作:-
**num1 = float(input('enter your first number :'))
op = input('choose your operator: ')
num2 = float(input('enter your second number :'))
operator = ('+', '-', '/', '*')
if op in operator:
print(num1 - num2)
elif op in operator:
print(num1 + num2)
elif op in operator:
print(num1 * num2)
elif op in operator:
print(num1 / num2)
else:
print('invalid operator')
我试图更改第一个代码(原始代码) 到我想自己编写的第二个代码。 但它只显示第一个运算符:- 我哪里做错了?
我想也许你需要这个
num1 = float(input('enter your first number :'))
op = input('choose your operator: ')
num2 = float(input('enter your second number :'))
operator = {
"-": lambda x, y: x - y,
"+": lambda x, y: x + y,
"/": lambda x, y: x / y,
"*": lambda x, y: x * y
}
if op in operator:
print(operator[op](num1, num2))
else:
print('invalid operator')