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

为何在Blackjack游戏函数中需返回pc_sum而非computers_cards?

为什么列表无需返回就能更新,而整数必须返回?

我正在开发一款Blackjack游戏,先编写电脑端行动逻辑,后续再实现用户端功能,最终通过对比双方手牌总和判定胜负。编写电脑行动逻辑时遇到一个问题:在pc_moves()函数中,无需返回computers_cards列表就能更新其内容,但必须返回pc_sum整数才能让外部获取更新后的值。我已解决问题,但不理解背后原因,相关代码如下:

import random
from art import logo
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
your_cards = []
computers_cards = []
game = True 
pc_sum = 0


def f_wants_to_play():
    global game
    wants_to_play = input("Do you want to play a game of Blackjack? Type 'y' or 'n':")
    if wants_to_play == "y":
      print(logo)
      print("blackjack")
    elif wants_to_play == "n":
      print("You don't wanna play! Goodbye!")
      game = False
    else:
      print("Type 'y' or 'n'!")
      f_wants_to_play() 

def pc_moves():
    global pc_sum
    global computers_cards
    computers_cards = random.sample(cards, 2)
    pc_sum = sum(computers_cards)
    print(f"computers cards: {computers_cards}")
    def add_new_card_pc(pc_sum, computers_cards):
      if pc_sum < 17:
        computers_cards.append(random.choice(cards))
        pc_sum = sum(computers_cards)
        return pc_sum
        if pc_sum > 21:
          if 11 in computers_cards:
            place_of_ace = computers_cards.index(11)
            computers_cards[place_of_ace] = 1
            pc_sum = sum(computers_cards)
            return pc_sum
            if pc_sum < 21:
              add_new_card_pc(pc_sum, computers_cards)
        else:
          add_new_card_pc(pc_sum, computers_cards)
      return pc_sum
    pc_sum = add_new_card_pc(pc_sum, computers_cards)
  
  
    
def blackjack():  
    while game == True:
      f_wants_to_play()
      if not game:
        break
      your_cards = random.sample(cards, 2)
      print(f"Your cards: {your_cards}, current score: {your_cards[0]+your_cards[1]}")
      user_sum = sum(your_cards)
      pc_moves()
      print(f"pc sum : {pc_sum} computers_cards: {computers_cards}")

    
blackjack() 

原因解析

核心区别在于Python里可变类型和不可变类型的特性:

  • 列表是可变类型:当你把computers_cards传入add_new_card_pc函数时,函数操作的是这个列表对象本身。比如append或者修改元素的操作,都是直接在原对象上修改,外部的computers_cards变量始终指向同一个对象,所以不需要返回就能看到更新后的内容。
  • 整数是不可变类型:整数一旦创建就不能被修改。当你在函数里执行pc_sum = sum(computers_cards)时,其实是创建了一个新的整数对象,函数内部的pc_sum变量会指向这个新对象,但外部的pc_sum还是原来的旧对象。所以必须把新的整数对象返回,让外部的pc_sum重新指向它,才能拿到更新后的值。

另外补充:你代码里的add_new_card_pc函数存在逻辑问题——return pc_sum之后的代码永远不会执行(比如处理超过21点转换A的逻辑),建议调整代码顺序,把return放到逻辑处理完成之后。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 12:15:56