含Or条件的While循环未正确求值问题求助
问题分析与修复方案
错误根源:循环条件逻辑完全错误。原代码用
or连接三个不等判断,不管输入的是1、2还是3,总有至少两个条件为真(比如输入1时,question !=2和question !=3都是True),所以or的结果永远是True,循环会无限执行。修复方案1:修正逻辑运算符
把or换成and,只有当输入同时不等于1、2、3时,才进入循环:
question = int(input("Enter a program 1.Arts 2.Science 3.Engineering: ")) while (question != 1) and (question != 2) and (question != 3): print("Invalid input. Please enter 1, 2, or 3") question = int(input("Enter a program 1.Arts 2.Science 3.Engineering: "))
- 修复方案2:更简洁的成员判断
用not in直接检查输入是否在合法集合里,代码可读性更强:
question = int(input("Enter a program 1.Arts 2.Science 3.Engineering: ")) while question not in {1, 2, 3}: print("Invalid input. Please enter 1, 2, or 3") question = int(input("Enter a program 1.Arts 2.Science 3.Engineering: "))
- 进阶优化:处理非整数输入
原代码如果用户输入字符串(比如"abc")会抛出ValueError,加异常处理让程序更健壮:
while True: try: question = int(input("Enter a program 1.Arts 2.Science 3.Engineering: ")) if question in {1, 2, 3}: break print("Invalid input. Please enter 1, 2, or 3") except ValueError: print("Please enter a valid integer (1, 2, or 3)")
内容的提问来源于stack exchange,提问作者Shez Zed
相关产品推荐
相关产品推荐

