我不知道是什么问题,但如果条件不足,我不能结束一个while循环.让我展示一下代码:
while True: k = input ("Please enter 'hello': ") if k == "hello": m = input ("Are your Sure? (Y/N): ") if m == "Y" or "y" or "yes" or "Yes": break
现在,在第二个提示之后,即使我输入no或任何其他内容,while循环仍然结束.我只想在第二次确认后结束它.编码中的错误是什么?
这就是内部发生的事情.
你的代码:
m == "Y" or "y" or "yes" or "Yes"
Python解读:
(m == "Y" )or ("y" or "yes") or "Yes"
("y" or "yes")
将总是产生y since it is not a falsey value
然后再("y" or "yes") or "Yes"
改为这个"y" or "Yes"
相同的值,所以最后(m == "Y" )or ("y" or "yes") or "Yes"
改为(m == "Y" )or "y"
为避免这种情况,您可以单独检查所有条件或in
BenC说明
或者更简单
m.lower() in "yes" # Note that it also True if m is e or es or s etc.. or "yes".startwith(m.lower()) # This work perfectly as per my test cases