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

Time:10-18

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!

CodePudding user response:

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:

  • if the user inputs an invalid number twice, you accept it the second time
  • it would be better to pass number_in to validateNumber as a parameter rather than relying on a global
  • if the user inputs something which is not an integer, the game terminates

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)

CodePudding user response:

After you get correct answer (number_in == game_1), you should break the while.

CodePudding user response:

I think, this is what you want:

from random import randint


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

    return valid


game_1 = randint(1, 6)
guess_was_correct = False

while not guess_was_correct:
    is_valid = False
    while not is_valid:
        try:
            number_in = int(input("Enter a number between 1-6: "))
            is_valid = validateNumber()
            if not is_valid:
                print("You entered a number outside of the 1-6 range. Please enter a number between 1 and 6!")
        except ValueError:
            print("You did not enter a number. Please enter a number.")

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

You need an inner loop to check the validity of the input, and the exception handling needs to go there too.

Checking the correctness of the guess is done in the outer loop. It's a separate thing and needs to be done only once we have a valid input.

  • Related