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

Python While循环不符合预期:输入1或2仍持续循环

问题分析与解决

你的代码循环停不下来的核心问题是逻辑判断错误:

你写的条件 (printType != 1) or (printType != 2) 永远为真,原因很简单:

  • 输入1时,printType !=2 是真,or 逻辑只要一个分支为真,整体就为真;
  • 输入2时,printType !=1 是真,同样满足or的条件,循环会一直执行。

修正后的代码方案

方案1:将or改为and

printType = int(input('Please select your print type. (1 or 2.): '))
if printType != 1 and printType != 2:
    while printType != 1 and printType != 2:
        print('Invalid input. Please select 1 or 2.')
        printType = int(input("1 or 2?: "))

方案2:更简洁的写法(合并判断与循环)

直接判断输入值是否不在允许的范围内,省去多余的if语句:

printType = int(input('Please select your print type. (1 or 2.): '))
while printType not in {1, 2}:
    print('Invalid input. Please select 1 or 2.')
    printType = int(input("1 or 2?: "))

内容的提问来源于stack exchange,提问作者qravy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:52:32