Python编写双骰子投掷程序触发无限循环无法提示输入问题求助
问题排查&修复方案
现有代码的3个核心错误
- 特殊点数判断逻辑完全错误:
(result1, result2)是存储两个骰子点数的元组,不可能等于整数1/6。蛇眼对应两个骰子都是1,即(result1, result2) == (1, 1);Boxcars(火车厢)对应两个骰子都是6,即(result1, result2) == (6, 6) - 是否继续投掷的提示逻辑位置错误:询问
choice2的代码被写在了Boxcars的判断分支内,只有触发了错误的Boxcars条件才会执行,绝大多数情况都不会走到这一步,自然不会弹出输入提示,choice1始终为y就会一直循环 - 输入函数写错:获取用户输入应该用
input(),你写的是print(),print()的返回值是None,就算走到这个分支也永远拿不到用户的输入内容
修正后的完整代码
import random print('Dice Roller') print() choice1 = input('Roll the dice? (y/n): ') possibleResults = [1, 2, 3, 4, 5, 6] while choice1.lower() == 'y': result1 = random.choice(possibleResults) result2 = random.choice(possibleResults) total = result1 + result2 print('Die 1: ', str(result1)) print('Die 2: ', str(result2)) print('Total: ', total) print() if (result1, result2) == (1, 1): print('Snake eyes!') print() elif (result1, result2) == (6, 6): print('Boxcars!') print() # 每次投掷结束都询问是否继续 choice2 = input('Roll again? (y/n): ') if choice2.lower() != 'y': break
补充优化点
- 把
import random和骰子点数列表possibleResults移到了循环外,避免重复执行冗余代码 - 增加了
lower()判断,兼容用户输入大写Y的场景
内容的提问来源于stack exchange,提问作者DokkanFred
相关产品推荐
相关产品推荐

