Search code examples
pythonexceptionwhile-loop

while loop could not break


there is NameError: name 'user' is not defined

why while loop is not ending please help to find the problem

this program is for dice roll in pyhton I want to roll the dice with no exception but there are exception accured


rand_num=random.randint(1, 6)
game_is_on=True    
while True:
    try:
        user=int(input("What's your choice : "))
        continue
    except:
        print("Please Enter 1-6")

    if user == rand_num:
        print("\t congrats ! \n You guessed it right 🎊")
    elif user != rand_num:
        print("Sorry! your guess is incorrect🥺")
        
    replay=input("Do you want to play again (Yes/No)")
    if replay =='yes'.lower():
        game_is_on=True
    else:
        print("Thanks for playing this game")
        game_is_on=False```


hlep to find the problem please



Solution

  • For your loop to exit:

    • Your while loop will forever be true, but you switched a variable game_is_on that was meant to regulated the loop. Instead of the forever loop , game_is_on should be next to while,
    • You need to remove continue statement as that line will just go to the next iteration as long as the condition is true,
    • When asked about replaying, the lower part should be on the variable, instead of lowering the string itself.

    Below is the code you need:

    rand_num=random.randint(1, 6)
    game_is_on=True
    # while True:    
    while game_is_on:
        try:
            user=int(input("What's your choice : "))
            # continue
        except:
            print("Please Enter 1-6")
    
        if user == rand_num:
            print("\t congrats ! \n You guessed it right 🎊")
        elif user != rand_num:
            print("Sorry! your guess is incorrect🥺")
            
        replay=input("Do you want to play again (Yes/No)")
        if replay.lower() =='yes':
            game_is_on=True
        else:
            print("Thanks for playing this game")
            game_is_on=False
    

    Happy coding!