You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python虚拟骰子程序选择不合并数值时输出异常问题求解

问题原因

  • 你当前写法里的no_add = str(random.randint(lowest, total)) * amount是先生成1个随机数,转成字符串后重复amount次,所以输出的都是同一个数字的重复结果,并非多个独立骰子的数值
  • 无需相加的随机数生成逻辑写在了滚动循环外部,仅会在程序启动时计算1次,后续多次重掷也不会生成新的数值
  • 另外存在隐藏问题:如果用户输入的相加选项既不属于yes也不属于no的集合,程序没有给lowest、total赋值,运行时会直接报错

修复方案

  1. 删除循环外的no_add相关代码,将无需相加的随机数生成逻辑移入rolling循环内部,保证每次重掷都会生成新的数值
  2. 无需相加时通过遍历生成amount个独立的随机数,再拼接输出
  3. 补充无效输入时的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 11:06:04