Sum 函数具有意外行为

Sum function has unexpected behavior

我在使用我定义的函数中的 sum() 函数时遇到问题。当我在不定义函数的情况下编写相同的代码时,一切正常。

new_game = input("Do you want to play a game of Blackjack? Type 'y' or 'n': \n")

while new_game == 'y':
  my_cards = []
  computer_cards = []
  cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
  # Dodaj 2 karty do każdej listy
  my_cards += random.sample(cards, 2)
  computer_cards += random.sample(cards, 2)
  my_score = 0
  computer_score = 0

  
  def sum_scores():
    my_score = sum(my_cards)
    return my_score
    computer_score = sum(computer_cards)
    return computer_score
    
    if my_score > 21:
      if 11 in my_cards:
        my_score = my_score - 10
        return my_score
    if computer_score > 21:
      if 11 in computer_cards:
        computer_score = computer_score - 10
        return computer_score
   
  sum_scores()
  print(f"Your cards: {my_cards}, current score: {my_score} ")
  print(f"Computer first card: {computer_cards[0]}")
  continue_game = input("Type 'y' to get another card, type 'n' to pass.")
  if continue_game == "n":
    break

一个函数只能return一次。一旦您的函数到达其第一个 return 语句,它就完成了:

  def sum_scores():
    my_score = sum(my_cards)
    return my_score
    # all done!

相反,等到你都完成了两个分数的计算后再return他们:

  def sum_scores(my_cards, computer_cards):
    my_score = sum(my_cards)
    computer_score = sum(computer_cards)
    
    if my_score > 21 and 11 in my_cards:
      my_score -= 10
    if computer_score > 21 and 11 in computer_cards:
      computer_score -= 10

    return my_score, computer_score

然后当您调用 sum_scores() 时,请确保将 return 值分配给变量,以便您可以在函数外使用它们:

  my_score, computer_score = sum_scores(my_cards, computer_cards)
  print(f"Your cards: {my_cards}, current score: {my_score} ")