我正在尝试用python创建我的第一个程序。我为两个数字(num1和num2)制作了一系列if语句。我所有的代码都适用于加,乘和除运算符,但是当我使用减法运算符时,要么没有收到消息,要么输出“无效运算符”。我确定我今天刚开始学习python时,就已经做了一些简单的错误,但是我将不胜感激。谢谢。
num1= float(input("enter first number:"))
operator = (input("enter operator:"))
num2= float(input("enter second number:"))
if operator== ("add" or "+" "sum"or "summation"):
print(num1+num2)
elif operator== ("multiply" or "multiplication" or"*"):
print(num1*num2)
elif operator== ("divide" or "division" or "/"):
print(num1/num2)
elif operator== ("minus" or "subtract" or "-"):
print(num1-num2)
else:
print("Invalid Operator")
输出:
C:\Users\clubj\PycharmProjects\untitled9\venv\Scripts\python.exe "C:/Users/clubj/PycharmProjects/untitled9/better calculator.py"
enter first number:32
enter operator:-
enter second number:6
Invalid Operator
以退出代码0结束的过程
以退出代码0结束的过程
答案 0 :(得分:0)
替换所有or,然后创建一个元组。 您的代码只有在您编写时才会
if (operator== "add") or (operator=="+") or (operator=="sum") or (operator =="summation"):
代替
operator== ("add" or "+" or "sum" or "summation"):
num1= float(input("enter first number:"))
operator = (input("enter operator:"))
num2= float(input("enter second number:"))
print(operator)
if operator in ("add", "+", "sum", "summation"):
print(num1+num2)
elif operator in ("multiply", "multiplication", "*"):
print(num1*num2)
elif operator in ("divide", "division", "/"):
print(num1/num2)
elif operator in ("minus", "subtract", "-"):
print(num1-num2)
else:
print("Invalid Operator")
答案 1 :(得分:0)
您也可以尝试python builtin function eval()
。评估函数通常用于需要评估mathematical
表达式的情况或应用程序中。同样,如果用户要将string
评估为code
,则可以使用eval函数,因为eval函数评估字符串表达式并返回整数作为结果。
num1= input("enter first number:")
operator = input("enter operator:")
num2= input("enter second number:")
if operator in ["+", '-', '/', '*', '//', '%']:
print(eval(num1+ operator+ num2))
else:
print("Invalid operator")