Python虚拟骰子程序选择不合并数值时输出异常问题求解
问题原因
- 你当前写法里的
no_add = str(random.randint(lowest, total)) * amount是先生成1个随机数,转成字符串后重复amount次,所以输出的都是同一个数字的重复结果,并非多个独立骰子的数值 - 无需相加的随机数生成逻辑写在了滚动循环外部,仅会在程序启动时计算1次,后续多次重掷也不会生成新的数值
- 另外存在隐藏问题:如果用户输入的相加选项既不属于yes也不属于no的集合,程序没有给
lowest、total赋值,运行时会直接报错
修复方案
- 删除循环外的
no_add相关代码,将无需相加的随机数生成逻辑移入rolling循环内部,保证每次重掷都会生成新的数值 - 无需相加时通过遍历生成
amount个独立的随机数,再拼接输出 - 补充无效输入时的
lowest、total赋值逻辑,避免运行报错,同时增加骰子数量合法性校验
修复后完整代码
import random import time running = True rolling = True yes = ("yes", 'y', 'Y', 'Yes', 'YES') no = ("no", 'n', 'N', 'No', 'NO') if running is True: print('Welcome to Virtual Dice.') time.sleep(0.5) sides = int(input('Pick the amount of sides: ')) amount = int(input('Pick the amount of dice: ')) # 补充骰子数量合法性校验 if amount <= 0: print("骰子数量不能小于1,程序退出") exit() add = input(f'Would you like to add the {amount} dice values together? ') if add in yes: total = sides * amount lowest = amount else: # 无效输入默认走不相加逻辑,统一赋值 total = sides lowest = 1 if add not in no: print("Invalid Input") print("Answering with no...") time.sleep(1) while rolling is True: print("Rolling....") time.sleep(1) if add in yes: print(random.randint(lowest, total)) else: # 每次重掷生成amount个独立的随机数 dice_list = [str(random.randint(lowest, total)) for _ in range(amount)] print(' '.join(dice_list)) ask = input("Do you want to roll more? (y/n): ") if ask in yes: rolling = True elif ask in no: rolling = False print("Thank you for using Virtual Dice.") time.sleep(0.5) print("Ending Virtual Dice...") time.sleep(1) else: print("Invalid Input") print("Ending Virtual Dice...") time.sleep(1) rolling = False
内容的提问来源于stack exchange,提问作者RBM
相关产品推荐
相关产品推荐

