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

Python Blackjack项目中可迭代解包后调用deal()无效果问题

问题根因

你遇到的问题和可迭代解包语法本身无关,是三个逻辑遗漏导致的:

  • 你在keep_playing()函数内调用deal()后,没有接收函数返回的新牌组,返回值被直接丢弃,不会自动更新你之前定义的全局player、dealer变量
  • 发新牌后的点数计算、手牌打印逻辑没有被重新触发,就算拿到新牌也看不到对应输出
  • 原代码缺少import random依赖导入,执行会直接报错
修复后可运行代码
import random

def deal():
  cards = [1,11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
  player = []
  dealer = []

  while len(player) < 2:
    player.append(random.choice(cards))
    dealer.append(random.choice(cards))

  return player, dealer

# 把单局游戏的完整逻辑封装为独立函数
def play_round():
    player, dealer = deal()
    player_cards = sum(player)
    dealer_cards = sum(dealer)
    print(f"Your cards are {player}. Total  = {player_cards}")
    print(f"The dealer shows [{dealer[0]}, *]. Total = {dealer_cards}")

def keep_playing():
  play_or_quit = input("Would you like to continue playing? Type 'Y' or 'N' ").lower()
  if play_or_quit == 'y':
    # 触发完整的新开局流程
    play_round()
    # 本轮结束后再次询问是否继续
    keep_playing()
  else:
    print('Thank you for playing, good luck.')

# 启动程序后先运行第一局
play_round()
keep_playing()
补充说明

如果你确实需要在全局作用域存储玩家/庄家的手牌,也可以用global关键字声明变量后更新,更推荐用上述封装单局逻辑的方案,避免全局变量污染导致的后续逻辑混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:06:05