Python实现用户y/n输入校验时合法输入仍触发错误提示问题
核心问题出在两处逻辑错误:
第一段代码的判断表达式语法逻辑错误
if sfpreq != 'y' or 'n'会被Python解析为(sfpreq != 'y') or ('n'),而非空字符串'n'的布尔值恒为True,所以不管用户输入任何内容,该判断条件永远成立,始终进入错误提示分支。第二段代码的逻辑运算符使用错误
你把判断补全为sfpreq != 'y' or sfpreq != 'n'后,误用了or(或)运算符:
- 当输入为
y时,sfpreq != 'n'为真,整体条件为真 - 当输入为
n时,sfpreq != 'y'为真,整体条件为真
也就是说不管输入是y还是n,该条件永远成立,自然始终触发错误提示。
修正方案
把or换成and即可,更推荐用成员判断的写法,可读性更高:
写法1:修正逻辑运算符
print ('Does this service require an SFP Module? (y/n): ') while True: sfpreq = input().strip() if sfpreq != 'y' and sfpreq != 'n': print("You must enter either y or n") continue else: break
写法2:更简洁的成员判断(推荐)
print ('Does this service require an SFP Module? (y/n): ') while True: sfpreq = input().strip() if sfpreq not in {'y', 'n'}: print("You must enter either y or n") continue break
代码中额外加的strip()方法用于过滤用户不小心输入的首尾空格,适配更多输入场景
内容的提问来源于stack exchange,提问作者r1kky
相关产品推荐
相关产品推荐

