Python3编写骰子投掷器出现无法按用户输入终止循环问题
Python骰子投掷器逻辑问题修复方案
问题原因
你写的多条件or判断存在语法逻辑错误:
在Python中,or运算符两侧是独立的布尔判断项,非空字符串的布尔值默认为True,你写的while repeat == 'Y' or 'y' or 'yes' or 'Yes'实际等价于:
while (repeat == 'Y') or True or True or True:
这个表达式的结果永远为True,所以无论输入什么内容,循环都会持续执行。同样的错误也出现在循环末尾的if判断里。
修复方案
1. 修正条件判断
可以用两种写法替换原有判断逻辑,更简洁也更易维护:
- 写法1:全量写全判断条件
while repeat == 'Y' or repeat == 'y' or repeat == 'yes' or repeat == 'Yes':
- 写法2:用成员判断+大小写转换,兼容性更强
while repeat.lower() in {'y', 'yes'}:
这种写法会自动把用户输入的内容转成小写,不管用户输入Yes、YES、Y都能正确匹配。
2. 补充其他代码隐含问题
你现有代码还有两个可以同步修正的问题:
- 骰子随机数定义在循环外,每次投掷的结果都是固定的,不会重新生成随机值,需要把
d100 = dice.randint(1,100)这类定义放到循环内部,每次投掷前重新生成 - 当前投掷多个骰子的计算逻辑是单骰子结果乘数量,不符合真实投掷规则,应该改为循环投掷对应数量的骰子累加结果
修正后完整示例代码
import random as dice repeat = 'Y' while repeat.lower() in {'y', 'yes'}: roll = input('What would you like to roll? A d100, d20, d10, d8, d6, d4, or d2?:') # 校验输入的骰子是否合法 if roll not in {'d100','d20','d10','d8','d6','d4','d2'}: print('That is not an available die! Please select a die.') continue quantity = input('How many would you like to roll?') quantity = int(quantity) total = 0 dice_side = int(roll.replace('d', '')) # 循环投掷对应数量的骰子累加结果 for _ in range(quantity): total += dice.randint(1, dice_side) print(f'You rolled a: {total}!') repeat = input('Would you like to continue?: ')
内容的提问来源于stack exchange,提问作者Owen Hall
相关产品推荐
相关产品推荐

