You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基础While循环输入验证问题:循环无法正常退出

Why Your While Loop Is Stuck in an Infinite Loop (Easy Fix!)

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, but temp != "2" is true → the or condition passes, loop continues.
  • If you type "2", temp != "2" is false, but temp != "1" is true → again, the or condition 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:27:33