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

制作Blackjack游戏时遇TypeError: 'int' object is not subscriptable错误求助

解决Blackjack游戏中的索引错误问题

错误原因分析

你遇到的TypeError: 'int' object is not subscriptable是因为**player_cards[0][1][2][3][4]的写法完全错误**:

  • player_cards是包含2个整数的列表(比如[11, 7]),player_cards[0]是列表里的第一个整数(比如11),整数类型不能再用[1]这种下标去访问,所以触发报错。
  • 你尝试转字符串时的错误,是因为错误的下标写法没改,反而把列表当成字符串处理,导致索引类型不匹配。

修正后的完整代码

import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
# 初始化游戏启动变量
blackjack_start = input("Type 'y' to start the game, 'n' to quit: ")

while blackjack_start == "y":
    # 玩家和电脑各抽2张牌
    player_cards = [random.choice(cards), random.choice(cards)]
    comp_cards = [random.choice(cards), random.choice(cards)]
    
    # 计算分数
    player_score = sum(player_cards)
    comp_score = sum(comp_cards)
    
    # 正确打印玩家卡片和电脑首张牌
    # 方式1:直接打印列表(简洁)
    print(f"Your Cards: {player_cards}, current score: {player_score}  Computer's first card: {comp_cards[0]}")
    # 方式2:格式化展示卡片(更友好)
    # print(f"Your Cards: {', '.join(map(str, player_cards))}, current score: {player_score}  Computer's first card: {comp_cards[0]}")
    
    hit = input("Type 'y' to get another card, type 'n' to pass: \n")
    # 游戏循环结束后询问是否再次开始
    blackjack_start = input("Type 'y' to play again, 'n' to quit: ")

关键修正点

  1. 导入random模块:原代码未导入random,运行会报错,必须添加import random。
  2. 初始化blackjack_start变量:原代码直接使用该变量但未定义,需要先让用户输入启动指令。
  3. 修正print语句:直接使用player_cards打印所有玩家卡片,或者用', '.join(map(str, player_cards))把列表转成逗号分隔的字符串,避免错误的下标写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:15:35