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

如何用Python列表与循环编写掷骰子游戏?解决NoneType报错问题

问题解决与代码完善

核心报错原因

list.remove()是原地修改列表的方法,返回值为None。你执行numbers_Berni = numbers_Berni.remove(rand)这类赋值语句后,变量会被覆盖成None,后续调用len(numbers_Berni)自然触发TypeError。

其他待修正问题

  • 逻辑错误:原代码直接从玩家剩余数字里随机选取,不符合“掷骰子生成1-6随机数,掷出对应数字才划掉”的规则
  • 拼写错误:random.choise应为random.choice;Rosa的操作提示误写为针对Rolf的内容
  • 交互缺失:原代码未处理用户输入,流程会直接跳过等待步骤

修正后的完整代码

import random

# 初始化三名玩家的数字列表
numbers_Berni = [1, 2, 3, 4, 5, 6]
numbers_Rolf = [1, 2, 3, 4, 5, 6]
numbers_Rosa = [1, 2, 3, 4, 5, 6]

print("Let's start, press ENTER to continue")
input()  # 等待用户按回车启动游戏

while len(numbers_Rolf) > 0 and len(numbers_Rosa) > 0 and len(numbers_Berni) > 0:
    # Berni回合
    print("\nPress ENTER to make Berni throw the dice")
    input()
    dice = random.randint(1, 6)  # 模拟掷骰子,生成1-6随机数
    print(f"Berni rolled a {dice}!")
    if dice in numbers_Berni:
        numbers_Berni.remove(dice)
        print(f"Berni crossed out {dice}! Remaining numbers: {numbers_Berni}")
    else:
        print(f"Berni already crossed out {dice}! Remaining numbers: {numbers_Berni}")
    if len(numbers_Berni) == 0:
        print("\nBerni wins!")
        print("Game over")
        break

    # Rolf回合
    print("\nPress ENTER to make Rolf throw the dice")
    input()
    dice = random.randint(1, 6)
    print(f"Rolf rolled a {dice}!")
    if dice in numbers_Rolf:
        numbers_Rolf.remove(dice)
        print(f"Rolf crossed out {dice}! Remaining numbers: {numbers_Rolf}")
    else:
        print(f"Rolf already crossed out {dice}! Remaining numbers: {numbers_Rolf}")
    if len(numbers_Rolf) == 0:
        print("\nRolf wins!")
        print("Game over")
        break

    # Rosa回合
    print("\nPress ENTER to make Rosa throw the dice")
    input()
    dice = random.randint(1, 6)
    print(f"Rosa rolled a {dice}!")
    if dice in numbers_Rosa:
        numbers_Rosa.remove(dice)
        print(f"Rosa crossed out {dice}! Remaining numbers: {numbers_Rosa}")
    else:
        print(f"Rosa already crossed out {dice}! Remaining numbers: {numbers_Rosa}")
    if len(numbers_Rosa) == 0:
        print("\nRosa wins!")
        print("Game over")
        break

关键修正点说明

  • 移除错误的赋值语句,直接调用list.remove()修改原列表
  • 用random.randint(1,6)模拟真实掷骰子的随机数生成逻辑
  • 添加input()语句实现用户交互流程
  • 修复拼写与提示文本错误
  • 调整while循环条件为and,确保任意玩家完成数字划除后立即终止游戏

内容的提问来源于stack exchange,提问作者Даша Хоменко

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:20:37