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
相关产品推荐
相关产品推荐

