'Sum function has unexpected behavior
I have a problem using the sum() function within my defined function. When I write the same code without defining a function everything works.
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
Solution 1:[1]
A function can only return once. As soon as your function gets to its first return statement, it's done:
def sum_scores():
my_score = sum(my_cards)
return my_score
# all done!
Instead, wait until you're all done computing the two scores before you return them:
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
and then when you call sum_scores(), make sure to assign the return values to variables so you can use them outside the function:
my_score, computer_score = sum_scores(my_cards, computer_cards)
print(f"Your cards: {my_cards}, current score: {my_score} ")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
