pythonloopsfor-loopwhile-loopdice

How to end a try loop in a dice game at the correct place?


I am trying to make a program where the player enters a number (1-6) to guess what a fair randomised dice lands on. Then it should stimulate the dice throw, and informs the player whether it was correct or not. It should continue to ask the player to guess by entering a number until the guess is correct.

If it is correct the game should end. If it is not correct the game continues to ask the player to select a number.

I have tried:

from random import randint


def validateNumber():
    valid = False
    if 1 <= number_in <=6:
        valid = True
        
    return valid

game_1 = randint(1,6)

while True:
    try:
        number_in = int(input("Enter a number between 1-6: "))
        is_valid = validateNumber()
        if not is_valid:            
            number_in = int(input("Enter a number between 1-6: "))

        if number_in == game_1:
            print(f"The result was {game_1}. Your guess was correct!")
        else:
            print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
    except ValueError:            
            break

However, now it does not end when the guess is correct. Does anyone know how to fix this? I have tried many variants, but this is the closest I got to the wanted result, but still it is not satisfactory. Also it does not seem to truly handle the user input?

(I am quite new to Python and trying to learn the most before starting college in January:)) All help appreciated!


Solution

  • Your main issue is that you should break out of the while loop when the user guess the number. You have a couple of other issues:

    Note also you can simplify validateNumber as follows:

    def validateNumber(number):
        return 1 <= number <= 6
    

    Overall I would rewrite the code as:

    from random import randint
    
    def validateNumber(number):
        return 1 <= number <= 6
    
    game_1 = randint(1, 6)
    while True:
        # play game
        is_valid = False
        while not is_valid:
            # read an input
            try:
                number_in = int(input("Enter a number between 1-6: "))
                is_valid = validateNumber(number_in)
            except ValueError:            
                pass
        # check the input
        if number_in == game_1:
            print(f"The result was {game_1}. Your guess was correct!")
            # all done
            break
        else:
            print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
            # get another number for them to guess
            game_1 = randint(1, 6)