Your own While/Else


#1

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


Oops, try again.
Your code looks a bit off. Check the Hint if you need help! Your
code threw the following error: invalid syntax (python, line 6)

After looking through the other help topics, it appears that line 6 (if guess == random_number:)should be correct.


from random import randint
random_number = randint(1, 10)

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!"


#2

Be careful about where you've positioned your else clause; at the moment it's attached to the if statement, which means that if a user guesses incorrectly just once they received the message "You lose!"

You need to have the else attached to the while loop rather than the if statement.


#3

Thank you for the reply. Does this mean that it should not be indented, or that it should come immediately after the while? The below still doesn't work:

    from random import randint
    random_number = randint(1, 10)

    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!"

    Error:   File "python", line 7
        if guess == random_number:
                                 ^
    SyntaxError: invalid syntax

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

EDIT: Please format your code - moderator


#4

Ah, there's a problem I didn't spot before!

On line 6 (guess = int...) you're missing a closing parenthesis.

That's why it thinks the next line is wrong, because it's still waiting for ')'.


#5

Wow! Thanks so much :sunny: