Excuse my syntax or communication I am new to stackoverflow. I am building the below code and I am getting an error that states the following:
Traceback (most recent call last): File "main.py", line 58, in add_total_c() File "main.py", line 43, in add_total_c computer_total += computers_card[total_c] UnboundLocalError: local variable 'computer_total' referenced before assignment
I understand that it means I am trying to reference a variable before its being called out. but that doesn't make sense to me because computer_total is being referenced after the variable has been set in memory. I have bold specific code below for visual. In my head I feel that having the variables listed above first allows the below code to be referenced. but for some reason when calling the function it feels the variable doesn't exist?
please let me know what you think and how to solve. I prefer examples if available.
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
computers_card = []
user_card = []
computer_total = 0 # Here
user_total = 0
def deal_computer():
for c_card in range (1, 3):
computers_card.append(cards[random.randint(0, len(cards))])
def deal_user():
for u_card in range (1, 3):
user_card.append(cards[random.randint(0, len(cards))])
def initial_cards():
deal_computer()
deal_user()
def add_total_c():
for total_c in range(0,len(computers_card)):
computer_total += computers_card[total_c] # <--
def add_total_u():
for total_u in range(0, len(user_card)):
user_total += user_card[total_u]
print(f"Your cards: {user_card}")
print(f"Computer's first cards: {computers_card}")
initial_cards()
choice = input("Type 'y' for another card or 'n' to stand with your current cards")
if choice == "n":
add_total_c()
add_total_u()
stand = True
while stand:
if computer_total > 17 and computer_total < 21:
if user_total > computer_total:
print("You Won!")
stand = False
else:
print("you lose!")
stand = False
if computer_total < 17:
computers_card.append(cards[random.randint(0, len(cards))])
add_total_c()
if computer_total > 21:
print("Computer Bust")
I have tried to placed the variables inside the functions so that the reference is available when that function code is needed. unfortunately that creates problems when I later have to reference that code again.
The issue is that the computer_total variable is defined outside the add_total_c() function, but when you try to modify it inside the function, Python considers it a local variable within the function's scope. To solve this, you need to explicitly tell Python to use the global variable computer_total instead of creating a new local one.
You can modify and use global keyword like this:
def add_total_c():
global computer_total # Use the global computer_total variable
for total_c in range(len(computers_card)):
computer_total += computers_card[total_c]