Jane Doe2 - 1 year ago 110
Python Question

# Guessing random number game python

My program is supposed to ask the user to guess a number between 0 and 100 however I can't seem to get the output right. At the moment if the the User number is greater than the random number, it prints out an infinite amount of "Your number is too high." Also if the first UserGuess is low, then all the following numbers will have the same prompt: ("Your number is too low") despite them being actually bigger than the random number. I have no idea what I am doing wrong. Any help would be greatly appreciated. Thank you!

``````from random import randint

def main():

guessesTaken = 0

randomNumber = randint(0,100)
#print(randomNumber)
giveUp = -1
UserGuess = int(input("Take a guess" + "(The random number is: " + str(randomNumber) + "): "))

while UserGuess != randomNumber:

guessesTaken += 1

if UserGuess < randomNumber:
UserGuess = int(input("Your guess is too high.Try again: "))

elif UserGuess > randomNumber:
UserGuess = int(input("Your guess is too high.Try again: "))

elif UserGuess == randomNumber or UserGuess == giveUp:
break

if UserGuess  == randomNumber:
guessesTaken = str(guessesTaken)
print("Yes, that is right!")
print("It took you " + guessesTaken +  " guesses")
if UserGuess == giveUp:
guessesTaken = str(guessesTaken)
randomNumber = str(randomNumber)
print("Better luck next time.")
print("You tried"+ guessesTaken +  " guesses")

return
print (main())

if __name__ == "__main__":
main()
``````

You need to get more user input once you're inside the loop. Consider

``````UserGuess = None

while UserGuess != randomNumber:
UserGuess = int(input("Take a guess" + "(The random number is: " + str(randomNumber) + "): "))
guessesTaken += 1
....
``````

As it stands, you're taking only the first guess. Then you're repeatedly reevaluating it. Since there's no chance for the user to change their guess, it loops infinitely.

Also, you'll want to change up the order of your if/elifs.

As it stands, the structure is

``````if guess (is too low)
if the guess (is not too low), and (is too high)
if the guess (is not too low), and (is not too high), and (is correct) or (is 'give up')
``````

A quick way to get it working would be

``````if   UserGuess == randomNumber or UserGuess == giveUp:
...
elif UserGuess > randomNumber:
...
elif UserGuess < randomNumber:
....
``````