问题描述
如果用户输入的不是“ Y”或“ N”,则该代码应返回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
解决方法
类似于数学运算和PEMDAS,布尔运算符(and
,or
,==
)都有一个“ order of operations”。现在,您要问两个问题:
noOrY是否等于Y?
noOrYes是否等于N?
使用括号固定操作顺序。
if not (noOrYes == "Y" or noOrYes == "N")
您可以改为这样做:
while True:
noOrYes = input(f"Do you want to continue? (Y/N)")
if noOrYes == "Y":
break
else :
print("Sorry,I didn't understand that.")
,
而不是询问“如果不是”。以下代码处理的每个输入都不是“是”或“否”的某些变体(例如,“是”,“不”等)。
# 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