"or" 运算符的错误使用

Incorrect use of "or" operator

如果用户的输入不是“Y”或“N”,代码应该是 return false。当用户键入“Y”时,它结束循环,但当用户键入“N”时,它仍然继续循环。如何纠正?

# Ask if they want to continue
    while True:
        
        noOrYes = input(f"Do you want to continue? (Y/N)")
        if not noOrYes == "Y" or noOrYes == "N":
            print("Sorry, I didn't understand that.")
            #better try again... Return to the start of the loop
            continue
        else: 
            #firstName & lastName was successfully parsed!
            #we're ready to exit the loop.
            print(f"break")
            break

您可以这样做:

while True: 
    noOrYes = input(f"Do you want to continue? (Y/N)")

    if noOrYes == "Y":
        break
    
    else : 
        print("Sorry, I didn't understand that.")

与数学运算和 PEMDAS 非常相似,布尔运算符(andor==)有一个“order of operations”。现在你在问两个问题:

noOrYes 不等于 Y 吗?

noOrYes 等于 N 吗?

使用括号修复运算顺序。 if not (noOrYes == "Y" or noOrYes == "N")

而不是问“如果不是”。下面的代码处理每一个不是“是”或“否”的变体的输入(例如“是”、“不”等)。

# Ask if they want to continue
while True:
    noOrYes = input(f"Do you want to continue? (Y/N)")
    if noOrYes.lower().startswith('y'):
        #User gave a proper response
        #we're ready to exit the loop.
        break
    elif noOrYes.lower().startswith('n'):
        #User gave a proper response,
        #we're ready to exit the loop.
        break
    else: 
        print("Sorry, I didn't understand that.")
        #Better try again... returning to the start of the loop
        continue