Dqnny Dqnny - 3 months ago 7
Python Question

Number guessing game, unable to take the next guess

Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.

I added some code to make sure that the guess that the user enters is a number, but for some reason, it only works for their first guess.

import random

x = random.randint(1, 100)
guess = input("Guess the number")

while guess.isnumeric() == True:

if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")

if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")

if x == int(guess):
print ("That is correct!")
break

if guess.isnumeric() == False:
print("Please enter a valid number")
guess = input("Guess the number")


I don't really know how to else to explain it. But for example, if I guess the number 20 as my first guess, it would output too high or too low depending on the randomly generated number, but after that, if I input a bunch of random letters it would give me an error that the guess could not be compared to the randomly generated number.

Answer

I've fixed your code for you. Try this:

import random

x = random.randint(1, 100)

while True:
    try:
        guess = int(raw_input("Guess the number: "))
    except ValueError:
        print("Not a valid number, try again!")
        continue

    if guess < x:
        print("Too low, guess again")

    elif guess > x:
        print("Too high, guess again")

    elif x == guess:
        print ("That is correct!")
        break

You don't need to prompt the user for input after every guess, that's what the first input prompt is for. Because we are specifying while True, the user will get prompted to input a number every single time unless they enter the correct number, which in that case, we break the infinite loop.

Additionally, we can put the input statement in a try block, because we are casting the input as an integer right there. If the user enters a string, the program would otherwise fail if it tried to cast it as an integer, but if we except ValueError: and then continue, we will alert the user that their input is invalid, and then prompt them for input once again.