基础While循环输入验证问题:循环无法正常退出
Hey, I see exactly what's going on here—your loop condition has a classic logical operator mix-up that's keeping it running forever. Let's break this down:
The Core Problem
Your while loop uses or like this:
while (temp!="1" or temp!="2"):
Think about what this means: the loop will run if temp isn't "1" OR temp isn't "2". But here's the thing—no matter what you input, one of these will always be true!
- If you type "1",
temp != "1"is false, buttemp != "2"is true → theorcondition passes, loop continues. - If you type "2",
temp != "2"is false, buttemp != "1"is true → again, theorcondition passes, loop keeps going.
That's why you can never exit the loop—this condition will always evaluate to True.
The Fixes
You have two clean ways to fix this:
1. Use and instead of or
We want the loop to run only when temp is neither "1" nor "2". So we need both conditions to be true at the same time:
temp = input("1 for yes/2 for no") while (temp != "1" and temp != "2"): print("please input 1 or 2") temp = input("1 for yes/2 for no") print(temp)
2. Use not in for better readability (Pythonic way)
This is even cleaner—check if temp isn't in the set of valid options:
temp = input("1 for yes/2 for no") while temp not in ("1", "2"): print("please input 1 or 2") temp = input("1 for yes/2 for no") print(temp)
Either of these will make your loop exit as soon as you enter "1" or "2".
内容的提问来源于stack exchange,提问作者930727fre

