-1

I am coding a guessing game where the user inputs an integer between 1 and 100 to try and guess the correct number (26). I have to count the number of guesses the user takes to get the correct number. I want to use try and except blocks to allow the user to keep trying until they guess it right.

Right now, my code only allows the user to input one ValueError. I don't want this, I want to keep inputting until I guess the number. Attached is my code. Any help is greatly appreciated!

ex: I want to input errors ("a", 4.20, "hello") and still have them count as guesses until I guess the number

"a" > 4.20 > "hello" > 26 => Guessed it in 3 tries

def guess(n):
    secret_number = 26
    if n < secret_number:
        return print("Too low!")
    elif n > secret_number:
        return print("Too high!")


def try_exp():
    try:
        n = int(input("What is your guess? "))
        return n
    except ValueError:
        n = int(input("Bad input! Try again: "))
        return n


def counter():
    print("Guess the secret number! Hint: it's an integer between 1 and 100... ")
    n = try_exp()
    i = 0
    while n != 26:
        guess(n)
        i += 1
        n = try_exp()
    print(f"You guessed it! It took you {i} guesses.")


counter()

elguero
  • 9
  • 2

1 Answers1

0

Instead of making try_exp like that, you can use a while loop that will first ask for input, and if the input is valid, then it will break out of the while loop. This is one way to implement it:

def try_exp():
    first_input = True
    while True:
        try:
            if first_input:
                n = int(input("What is your guess? "))
                return n
            else:
                n = int(input("Bad input! Try again: "))
                return n
        except ValueError:
            first_input = False

In this, we go through an infinite loop, and we have a flag that designates whether it is the first guess or if they have already guessed before. If it is the first guess, we ask them for input, and if it is the second guess, we tell them that they gave incorrect input and ask for more input. After receiving correct input, the function returns n. If the input is incorrect which is when it is not an integer, we set first_input as false. Then, the while loop loops again. It will keep on waiting for input until they submit an integer.

Nathan Jiang
  • 131
  • 1
  • 9