为何我的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
相关产品推荐
相关产品推荐

