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

Python 3.12开发Blackjack游戏时出现KeyError:0错误求助

解决Blackjack(二十一点)游戏中的KeyError:0问题

问题重现

你执行card1=random.choice(cards)和card2=random.choice(cards)时触发KeyError:0,相关代码片段如下:

import random
nplayers=int(input(f"Insert the number of players: "))
pplayers=1
cards={
    1: "A",
    2: "2",
    3: "3",
    4: "4",
    5: "5",
    6: "6",
    7: "7",
    8: "8",
    9: "9",
    10: ["10", "J", "Q", "K"],
    11: "A"
}
card1=random.choice(cards)
card2=random.choice(cards)
def give_cards():
    print(f"Player {pplayers} cards are: " + str(card1) +"; " + str(card2))
while pplayers<=nplayers:
    give_cards()
    pplayers+=1
    card1=random.choice(cards)
    card2=random.choice(cards)

错误原因

random.choice()函数要求传入序列类型(比如列表、元组),但你直接传入了字典:

  • 在Python 3.6及更早版本中,字典不属于序列,random.choice会尝试通过索引(如cards[0])访问元素,而你的字典没有0这个键,因此抛出KeyError:0;
  • 即使在Python 3.7+中(字典变为有序),random.choice(cards)会随机选取字典的键,但选到10时,card1会是数字10,而非对应的"10"/"J"/"Q"/"K",逻辑依然错误。

解决方案

核心修正点

  1. 先将字典的键转换为列表,再用random.choice随机选点数;
  2. 针对点数10对应的列表值,额外做一次随机选择,拿到具体的牌面;
  3. 避免使用全局变量传递牌面,改用函数参数或内部生成的方式,让代码更规范。

修正后的完整代码

import random

nplayers = int(input("Insert the number of players: "))
pplayers = 1

cards = {
    1: "A",
    2: "2",
    3: "3",
    4: "4",
    5: "5",
    6: "6",
    7: "7",
    8: "8",
    9: "9",
    10: ["10", "J", "Q", "K"],
    11: "A"
}

def get_random_card():
    # 随机选一个点数键
    point = random.choice(list(cards.keys()))
    card_val = cards[point]
    # 若对应值是列表,再随机选具体牌面
    if isinstance(card_val, list):
        return random.choice(card_val)
    return card_val

def give_cards(player_num):
    # 函数内部生成两张随机牌
    card1 = get_random_card()
    card2 = get_random_card()
    print(f"Player {player_num} cards are: {card1}; {card2}")

while pplayers <= nplayers:
    give_cards(pplayers)
    pplayers += 1

额外说明

  • 如果你想更贴近真实的二十一点游戏,可以把牌库改成包含4套完整牌的列表(比如["A","2",..."K"]*4),这样能模拟抽牌后移除的逻辑;
  • 全局变量容易引发意外的bug,后续开发尽量用函数参数、类属性等方式传递数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:50:14