如何用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,提问作者Даша Хоменко
相关产品推荐
相关产品推荐

