即使给出正确的输入,无限循环也不会中断



我想让用户选择"做点什么;。他们必须输入";是";或";否";以突破循环。然后用户输入("ui"(被存储在"ui"中;user_input"并在if语句中用于";做点什么;。我尝试了以下代码,但无论输入什么,循环都不会中断。

user_input = ""
while True:
try:
ui = input("Do something? (yes/no): ").lower()
if ui != "yes" or ui != "no":
raise Exception

except Exception:
print(f"Error: {ui} is not a choice")

else:
print("Found no Errors")
user_input = ui
break

if user_input == "yes":
print("Did somethin")
elif user_input == "no":
print("Did nothing")

尽量保持简单。你可以修改这个,使它更简单。

user_input = ""
answer = False #assign bool variable to test the condition
#loop while the condition is true
while answer != True:
try:
ui = input("Do something? (yes/no): ").lower()

if ui == 'yes' or ui == 'no':
print("Found no Errors")
user_input = ui
if ui == "yes":
print("Did something")
else:
print("Did nothing")

answer == True #condition becomes false
#break the loop
break
#raise exception if condition is false    
else:
raise Exception

except Exception:
print(f"Error: {ui} is not a choice")