如何修复掷骰子程序循环异常:输入yes即退出的问题?
掷骰子代码的问题分析与修复方案
嘿,我一眼就瞅出你代码里的小bug啦!问题出在while循环的判断条件上:
你写的while repeat == ('y' or 'yes')在Python里并不会按你预想的那样工作——因为逻辑或or运算符会返回第一个为“真”的值,非空字符串都是真,所以('y' or 'yes')的结果其实是'y'。这就导致只有当输入是'y'时才会继续循环,输入'yes'自然就不满足条件,直接退出了。
两种修复方案:
方案1:用成员运算符判断(推荐,更简洁)
把循环条件改成判断输入值是否在包含允许值的集合/列表里:
from random import randint repeat = 'y' while repeat in {'y', 'yes'}: # 用集合或者['y', 'yes']都可以 print('your dice is', randint(1,6)) print('Do you want to roll again? (y/yes to continue)') repeat = input().lower() else: print('have a nice day')
方案2:拆分逻辑或判断
如果习惯用or,需要分别判断每个值:
from random import randint repeat = 'y' while repeat == 'y' or repeat == 'yes': print('your dice is', randint(1,6)) print('Do you want to roll again?') repeat = input().lower() else: print('have a nice day')
小优化建议
可以在提示语里明确告诉用户允许的输入值,比如print('Do you want to roll again? (y/yes to keep going, other keys to exit)'),这样用户体验会更好~
内容的提问来源于stack exchange,提问作者gatorcoder
相关产品推荐
相关产品推荐

