So I'm, coding a blackJack game,and I made a list called user_score and computer_score. I used the random module to choose a random int from a list called cards. But when I use .append() to add the random choice from cards, it doesn't appear to be adding the random card to user_card / computer_card? Here is where I define it, and where I use the random module:
import random
user_score = 0
computer_score = 0
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
user_cards = []
computer_cards = []
def deal_card():
cards_left = 2
while not cards_left == 0:
random_user = random.choice(cards)
random_computer = random.choice(cards)
user_cards.append(random_user)
computer_cards.append(random_computer)
cards_left -= 1
print(user_score, computer_score)
and finally, this is where I call the function:
deal_card()
calculate_score(card_list=[user_score, computer_score])
calculate_score is defined here:
def calculate_score(card_list):
user_score = sum(user_cards)
computer_score = sum(computer_cards)
if computer_cards.count(11) > 0 and computer_cards.count(10) > 0:
computer_score = 0
elif user_cards.count(11) > 0 and user_cards.count(10) > 0:
user_score = 0
if user_cards.count(11) > 0:
cards.remove(11)
cards.append(1)
elif computer_cards.count(11) > 0:
cards.remove(11)
cards.append(1)
return user_score
PS: I'm still learning python, so please don't go to advanced
The issue is that the variables
user_cardsandcomputer_cardsare not in the scope ofdeal_card()orcalculate_score(). As mentioned in the previous answers, one way to deal with this problem is by usingglobalvariables. Another way to solve this, would be bypassingandreturningvariables in your functions: