我正在用Python开发一个简单的计算器程序,而且我很难理解为什么while循环仅在检查变量是否为有效运算符时使用“ and”时才有效。从逻辑上讲,我希望它检查输入是否为“ +”或“-”等。
这是循环:
operator = input("Enter operator: ")
while operator != "+" and operator != "-" and operator != "*" and operator != "/":
operator = input("Enter a valid operator: ")
我特别困惑,因为它似乎在另一个循环中按预期工作:
while num1 == "0" or num1.isdigit() == False:
print("You must enter a valid number that is not 0!")
num1 = input("Enter first number: ")
答案 0 :(得分:2)
对于Python 3,您可以按照以下方式进行操作:
operator = input("Enter operator: ")
while operator not in '+-*/':
operator = input("Enter a valid operator: ")
而且,在使用它的同时,最好使用字典和operator module来进行测试和分配,以避免以后出现if then if then ladder:
import operator
operators={'+':operator.__add__,
'/':operator.__truediv__,
'*':operator.__mul__,
'-':operator.__sub__}
op = input("Enter operator: ")
while op not in operators:
op = input("Enter a valid operator: ")
使用Python 2提防input
对所键入的内容进行评估(可能会带来不良后果)。
如果您使用的是Python 2:
operator = raw_input("Enter operator: ")
while operator not in '+-*/':
operator = raw_input("Enter a valid operator: ")