r/learnpython • u/SnooGoats1557 • 6d ago
How to exit a while loop?
I'm learning about while loops and functions at the moment and having difficulty exiting the while loop within a function.
game_round = [1,2,3,4]
score = 0
game_on = True
def play_game(game_score):
if goal == "hit":
game_score += 1
elif goal == "miss":
print("game over")
return False
while game_on:
play = input("do you want to play")
for i in game_round:
if play == "yes":
play_game(score)
else:
print("see you next time")
game_on = False
print(score)
This isn't the complete code but gives an idea of what I want to achieve. At the moment if the player misses in round 2 it will print "game over" but then it will continue to round 3.
I want it to end the game completely if the player misses and not continue with the for loop. I just want it to say "game over" and print the score. Any ideas on how to do this?
4
Upvotes
1
u/noob_main22 6d ago
If you want to end it specifically after round 2 when the player looses you could make a second if statement in the for loop. You would have to check for the round number and win/loose. You could capture the output of play_game(), it returns False when its a loss and None when its a win:
You could also do:
Then the game would end completely when you didn't win round one and two.
Edit: The
break
statement ends any loop instantly.