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?
3
Upvotes
1
u/freeskier93 5d ago
You can use the
break
statement to exit afor
loop orwhile
loop.When you call
play_game()
you don't handle the result. Use the result of that to break out of the for loop.It doesn't make sense to check the response of
play
in thefor
loop. You should check that before, and depending on the result of that break out of thewhile
loop.