0

i have a noob question. I'm trying to make a blackjack and in my "turn" function i put a variable change to False. I have no clue why it doesnt work... It says local variable is never used, but how's that possible if it is used in the while loop...

import random
p1 = []
p2 = []
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
# --------------------Game on/off
game_on = True

# -----------------Random card

def pick_card(x):
  return x.append(random.choice(cards))

# ---------------- calculate score :
  
def calculate_score(x):
  if len(x)==2 and sum(x) ==21:
    return 0
  if sum(x)>21:
    if x.count(11):
      x.remove(11)
      x.append(1)
      return sum(x)
    
  return sum(x)

# ------------------------
def turn(x):
  pick_card(x)
  if calculate_score(x) == 0:
    print("blackjack")
    game_on= False
  elif calculate_score(x) >21:
    print("You lost")
    game_on= False
  else:
    print(p1)


pick_card(p1)
pick_card(p2)
pick_card(p2)
while game_on:
  turn(p1)
  if input("continue?\n") == "y":
    game_on = True
  else:
    game_on=False
1
  • If a variable is set anywhere in a function it is seen as local to this function (if not explicitly declared as "global") and shadows (hides) a global variable of same name. Because this local variable is only set but never read it is seen as unused. Commented Oct 22, 2022 at 11:53

1 Answer 1

1

You have to set game_on variable as global:

def turn(x):
    global game_on
    pick_card(x)
    if calculate_score(x) == 0:
        print("blackjack")
        game_on = False
    elif calculate_score(x) > 21:
        print("You lost")
        game_on = False
    else:
        print(p1)

Also, fix your indentations.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. Appriciate the help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.