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

Python骰子模拟器问题:如何将随机掷骰结果存入列表?

解决骰子模拟器结果存入列表的问题
  • 问题根源:你把print(random.randint(1,6))的结果赋值给了dice_roll_result,但print()函数本身没有返回值(返回None),所以每次添加到列表的都是None,导致输入"stat"显示[None, None]。

  • 修复核心代码:先生成随机数并保存到变量,再打印这个变量,最后把变量加入列表:

# 替换原来的两行错误代码
dice_roll_result = random.randint(1, 6)
print(dice_roll_result)
rolled_numbers.append(dice_roll_result)
  • 优化整体逻辑(可选):
    • 输入"no"后需要退出循环,否则程序会继续执行后续判断
    • 统一输入转小写,兼容大小写输入
    • 简化次数控制逻辑,让代码更易读

修改后的完整代码:

import random

rolled_numbers = []
roll_count = 0
MAX_ROLLS = 5

while True:
    dice_roll = input("Do you want to roll a dice? ").lower()

    if dice_roll == "yes":
        if roll_count >= MAX_ROLLS:
            print("已达到最大掷骰次数(5次),程序结束")
            break
        result = random.randint(1, 6)
        print(f"掷出点数:{result}")
        rolled_numbers.append(result)
        roll_count += 1

    elif dice_roll == "no":
        print("Have a wonderful day. Come back to play again!")
        break

    elif dice_roll == "stat":
        print(f"已掷骰结果:{rolled_numbers}")

    else:
        print("无效输入,请输入yes/no/stat")

内容的提问来源于stack exchange,提问作者dEvSoVi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:55:08