Exercise 7 Question



File "python", line 14
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!"
    count += 1
        print "Guess again:"
    print "You lose."


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


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



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