maxhub
maxhub

Reputation: 1

While Loop not breaking when it is supposed to

def NewCard():
  draw_card = input("Would you like to draw a new card? 'hit' or 'pass': ").lower()
  if draw_card == "hit":
    new_card =  cards[random.randint(0, cards_length)]
    player_cards.append(new_card)
    print(f"Your new hand is {player_cards}")
  elif draw_card == "pass":
     playerturn = False
     return playerturn 

while playerturn == True:
  Check_Scores()
  NewCard()
ComputerPlays()

What is supposed to happen is that when the user types "pass" the while loop will break moving on to the next code. But what happens is that the loop repeats forever. This whole block is in another bigger function so that is why it is indented

Upvotes: 0

Views: 69

Answers (4)

khandelwal.pranshu
khandelwal.pranshu

Reputation: 11

Here the variable playerturn in function NewCard() is local to the function itself. Either use the global variable playerturn or modify your loop as below:

while playerturn==True:
    Check_Scores()
    playerturn=NewCard()

Upvotes: 1

maxhub
maxhub

Reputation: 1

def NewCard():
  draw_card = input("Would you like to draw a new card? 'hit' or 'pass': ").lower()
  if draw_card == "hit":
    new_card =  cards[random.randint(0, cards_length)]
    player_cards.append(new_card)
    print(f"Your new hand is {player_cards}")
  elif draw_card == "pass":
     global playerturn
     playerturn = False
 

while playerturn == True:
  Check_Scores()
  NewCard()
ComputerPlays()

setting playerturn as a global fixed my issue

Upvotes: 0

SmartOinker
SmartOinker

Reputation: 136

playerturn = True

def NewCard():
  global playerturn
  draw_card = input("Would you like to draw a new card? 'hit' or 'pass': ").lower()
  if draw_card == "hit":
    new_card =  cards[random.randint(0, cards_length)]
    player_cards.append(new_card)
    print(f"Your new hand is {player_cards}")
  elif draw_card == "pass":
     playerturn = False
     return playerturn 

while playerturn == True:
  Check_Scores()
  NewCard()
ComputerPlays()

You will need to add a global playerturn inside your NewCard() function for your code to work. This is because the playerturn = False line in your NewCard() function actually creates a local variable playerturn and sets it to False within the scope of the function, and it would not affect the value of playerturn outside the NewCard() function. For more information on python scopes, please read this article.

Upvotes: 1

QWERTYL
QWERTYL

Reputation: 1373

The playerturn variable in the NewCard function is local, not global. Try this:

while playerturn == True:
  Check_Scores()
  playerturn = NewCard()

Upvotes: 0

Related Questions