0

I am pretty new in Python, and as I am trying to complete a project of the course I am following I found myself stuck. It's a simple Blackjack emulator, where if the user type 'y' the script keeps dealing cards as long as the sum of the card at hand is less than 21. In case the user types 'n'or the sum of the card at hand is more than 21 the game stops and displays the score and who won.

To do this I set a variable to True at the beginning, that gets turned False if the the user types 'n'or the sum is greater than 21.

However the script doesn't turn it False if the user presses 'n', the script keep printing "Type 'y' to get another card, type 'n' to pass: " and the script keeps running in perpetuity, why is that? Why is the function not turned false. Thank for anyone who can help!

from art import logo
    import random
    
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    my_hand=[]
    dealer_hand=[]
    
    def hand():
      continue_play=input("Type 'y' to get another card, type 'n' to pass: ")
      
      if continue_play =='y':
        my_hand.append(random.choice(cards))
        dealer_hand.append(random.choice(cards))
        
        if sum(my_hand) > 21:
          print(f"Your final hand: {my_hand}, final score: {sum(my_hand)}")
          print(f"Computers final hand: {dealer_hand}, final score: {sum(dealer_hand)}")
          print("You went over. You lose ")
          playing=False
          
        elif sum(my_hand) <= 21:
          print(f"Your cards: {my_hand}, current score: {sum(my_hand)}")
          print(f"Computers first card: {dealer_hand[0]}")
    
      elif continue_play =='n':
        sumz=sum(dealer_hand)
        while sumz<17:
          dealer_hand.append(random.choice(cards))
          sumz=sum(dealer_hand)
          playing=False
        
    first_play=input("Do you want to play a game of Blackjack? Type 'y' or 'n': ")
    
    if first_play=='y':
      print(logo)
      my_hand=random.sample(cards,2)
      dealer_hand=random.sample(cards,2)
      print(f"Your cards: {my_hand}, current score: {sum(my_hand)}")
      print(f"Computers first card: {dealer_hand[0]}")
    
    playing=True
    
    while playing is True:
      hand()
    
    my_final_hand=sum(my_hand)
    dealer_final_hand=sum(dealer_hand)
    
    if my_final_hand==dealer_final_hand:
      print("It is a Draw")
    if my_final_hand<dealer_final_hand:
      print("dealer Win")
    if my_final_hand>dealer_final_hand:
      print("you Win")
Salah
  • 9
  • 3
  • At the beginning of your `hand()` function, you need to specify `nonlocal playing` in order to be able to assign a new value to `playing` in the enclosing scope (i.e. the outer function) – slothrop Apr 21 '23 at 14:41
  • See also: https://stackoverflow.com/questions/1261875/what-does-nonlocal-do-in-python-3 – slothrop Apr 21 '23 at 14:42

0 Answers0