Your own while / else


I was experimenting a little bit with this code and wanted to see what would happen if I made the program guide the user to the correct number. With this code there are instances where it will tell me to go higher or lower with my guess even tho I have already guessed that number or it is out of the range. Here is an example of what popped up in the window:

Your guess: 5
Your guess: 6
Your guess: 7
Your guess: 6
You win!

If 6 was the number I should have guessed then it should've told me the first time right? I would just like to know what I could change in the code to always get the right answer.


from random import randint

guesses_left = 5

while guesses_left > 0:
    random_number = randint(1, 10)
    guess = int(raw_input("Your guess: "))
    if guess == random_number:
        print "You win!"
    elif guess - random_number > 0:
        print "Lower"
    elif guess - random_number < 0:
        print "Higher"
    guesses_left -= 1

    print "You lose"


you should generate the random number before the loop

now each iteration of the loop, you generate a new random number


That makes a lot of sense. I figured it might have been regenerating the number each time. Thank you!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.