Python 使用;及;而不是",;或;在一段时间内循环
我正在用Python编写一个简单的计算器程序,我很难理解为什么这个while循环只有在我使用“and”检查变量是否为有效运算符时才起作用。逻辑上,我希望它检查输入是“+”还是“-”,等等 以下是循环:Python 使用;及;而不是",;或;在一段时间内循环,python,Python,我正在用Python编写一个简单的计算器程序,我很难理解为什么这个while循环只有在我使用“and”检查变量是否为有效运算符时才起作用。逻辑上,我希望它检查输入是“+”还是“-”,等等 以下是循环: operator = input("Enter operator: ") while operator != "+" and operator != "-" and operator != "*" and operator != "/": operator = input("Enter a
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: ")
对于Python 3,您可以按照以下方式进行操作:
operator = input("Enter operator: ")
while operator not in '+-*/':
operator = input("Enter a valid operator: ")
而且,在您进行测试时,您还可以使用字典和同时进行测试和分配,以避免以后出现以下情况:
使用Python2时要注意,input
会对键入的内容进行评估(可能会产生不良后果)
如果您使用的是Python 2:
operator = raw_input("Enter operator: ")
while operator not in '+-*/':
operator = raw_input("Enter a valid operator: ")
操作员!=“+”和运算符!=“-”和操作员!=“*”和运算符!=“/”
相当于not(运算符==“+”或运算符==“-”或运算符==“*”或运算符==”/”
。使用not
在和之间转换,而或是通过完成的。这是因为您使用的是=第一个示例中的code>和第二个示例中的=
。一个是包含的==
,另一个是独占的=代码>,因此它们需要不同的运算符来正确链接。拿着=代码>大小写,如果使用或
则它将始终计算为true,因为它必须不等于测试值之一。对于=
来说,使用和
是不正确的,因为某个事物不能等于多个事物。
operator = raw_input("Enter operator: ")
while operator not in '+-*/':
operator = raw_input("Enter a valid operator: ")