Your own while / else


#1



https://www.codecademy.com/courses/python-beginner-en-cxMGf/0/8?curriculum_id=4f89dab3d788890003000096


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
Higher
Your guess: 6
Higher
Your guess: 7
Lower
Your guess: 6
You win!
None


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.

Thanks!


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!"
        break
    elif guess - random_number > 0:
        print "Lower"
    elif guess - random_number < 0:
        print "Higher"
    
    guesses_left -= 1

else:
    print "You lose"


#2

you should generate the random number before the loop

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


#3

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


#4

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