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

Python双条件while not输入校验无法识别合法输入问题求解

问题原因

你的输入校验逻辑出错的核心是循环条件的逻辑运算符使用错误:
原条件 while not behaviour == 'A' or not behaviour == 'F' 永远为真,不可能退出循环:

  • 当你输入合法值A时,not behaviour == 'F' 结果为真,or 连接的条件整体为真,循环继续执行
  • 当你输入合法值F时,not behaviour == 'A' 结果为真,or 连接的条件整体为真,循环继续执行
  • 输入其他非法值时,两个条件都为真,循环当然继续执行
解决方案

你可以任选以下两种修正方式之一,更推荐第二种,可读性更高:

  1. 把逻辑运算符or替换为and,符合德摩根定律的逻辑要求
  2. 改用成员判断语法,直接校验输入是否在合法值范围内

修正后完整代码

cat_behaviour= []

print("\nIs the cat (A)ggressive or (F)riendly?\n")
behaviour = input().upper()

# 用成员判断做校验,逻辑清晰不易出错
while behaviour not in ('A', 'F'):
    print("You have entered a wrong input. Please enter A for aggressive or F for Friendly")
    behaviour = input().upper()
    
cat_behaviour.append(behaviour)

如果你想用原来的等式判断写法,把while条件改成下面这样也可以正常运行:

while not (behaviour == 'A' or behaviour == 'F'):

或者

while behaviour != 'A' and behaviour != 'F':

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:42:03