i am writing a blackjack game. At the beginning i am writing pc moves then i will code user's moves, at the end by comparing the summaries of the computers cards and users cards who is going to win will be decided. While i was coding pc moves i came across with a problem. i solved it but i don't understand why it is like that. i had to return pc_sum integer from function but not computers_cards list. New value to Computers_cards list is added without returning from the function. But pc_sum integer is not returned so i had to write "return pc_sum" in the pc_moves() function. Why is it like that? here is the code:
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()
Why i had to return pc_sum from pc_moves() but not computers_cards?
Lists are mutable, so you can modify the list that was passed as an argument inside the function, which can be observed by the code calling the function.
Integers are immutable, so you cannot modify the existing one and have no other choice but to return a new one to the calling code.