8. Your own while/else


#1



Hi guys! really stuck on this one so any help will be greatly appreciated!
I am basically confused about the logical flow behind what I type, so here it goes:

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


Error says: Did you print the "You win!" message?
No syntax error according to the programme.

I am expecting a correct response to trigger the "You win!" if statement below, but instead it triggers "You lose." else statement.


from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
print random_number
guesses_left = 3
guess = int(raw_input("Your guess: "))

while guess != random_number and guesses_left > 0:
    guess = int(raw_input("Your guess is incorrect. Plase try again: "))
    print "Guesses left: %s" % guesses_left
    if guess == random_number:
        print "You win!"
        break
    guesses_left -= 1
else:
    print "You lose."


What's wrong with my code? please help! :slight_smile:
Thanks a bunch!


#3

You never enter that loop, so there's no way it'll reach the win message

Your problem isn't really with the code, it's that you haven't thought out what order things should happen


#4

because you have guess != random_number it will skip the while loop and go to else

you will need to remove guess != random_number and setup another way to find if that is the correct answer and if not run the while loop


#5

you have a lot of unnecessary code. mine looks like so:

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
print random_number
guesses_left = 3
while guesses_left > 0:
    guess = int(raw_input("Your guess: "))
    if guess == random_number:
        print 'You win!'
        break
    guesses_left-=1
else: print 'You lose.'

#6

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