Exercise 7 Question


#1



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


File "python", line 14
else:
^
SyntaxError: invalid syntax


What I'm asking here is a more theoretical question...I passed the exercise after playing around with it a bit.

Why does the following code return the above error? Why can't I have an 'else' statement following my 'if' statement inside the while loop, with a separate else statement following the loop?

What I wanted to do was:

If they guess correctly, they win. Else (ie. if they make a wrong guess), the program should prompt them for another by printing "Guess again:".


import random

print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"

count = 0
while count < 3:
    num = random.randint(1, 6)
    print num
    if num == 5:
        print "Sorry, you lose!"
        break
    count += 1
    else:
        print "Guess again:"
else:
    print "You lose."


#2

You can only have else after an if, but in your code there is count += 1 between the if and else branches.


#3

You're right, I tried it and it works if I move that count += 1 inside the 'else' statement.

Thanks!!


#4

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