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

为何我的while循环语句未按预期运行?

问题分析与解决

先看你写的代码:

player = input('do you wanna play the game').lower()

while player != 'yes' or 'no':

    player = input('say yes or no')

if player == 'yes':
   print('ok')
else:
    quit()

问题出在while循环的条件判断上:player != 'yes' or 'no' 这个写法完全不符合你想要的逻辑。在Python里,非空字符串'no'会被直接判定为True,所以不管player的值是什么,整个条件表达式的结果永远是True,循环自然会一直跑下去,根本不会跳出。

你想要的逻辑是:当输入既不是yes也不是no时,才继续循环。正确的条件写法有两种:

  • 用not in判断是否不在指定的合法值里:while player not in ('yes', 'no')
  • 用and连接两个否定判断:while player != 'yes' and player != 'no'

修正后的完整代码可以是这样:

player = input('do you wanna play the game?').lower()

while player not in ('yes', 'no'):
    player = input('say yes or no').lower()  # 这里最好也加个lower(),避免大小写问题

if player == 'yes':
    print('ok')
else:
    quit()

这样就能实现你想要的效果:输入yes或no时跳出循环,进入后续的if-else判断;输入其他内容时,一直停在循环里提示重新输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:17:03