Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Python 3.1 throwing a SyntaxError when printing after loop?

I'm trying to run this snippet in Python 3.1 console and I'm getting SyntaxError:

>>> while True:
...     a=5
...     if a<6:
...             break
... print("hello")
  File "<stdin>", line 5
    print("hello")
        ^
SyntaxError: invalid syntax
>>>

(This is just shortened code to make a point.)

Am I missing something? Is there some other Magic I don't know about?

like image 674
bubersson Avatar asked Dec 06 '22 02:12

bubersson


2 Answers

You have to input an empty line into the REPL to complete the current block before you can enter a new, unindented line of code.

like image 142
Ignacio Vazquez-Abrams Avatar answered Dec 10 '22 11:12

Ignacio Vazquez-Abrams


It's working, if you put the whole thing in a function:

def test():
    while True:
        a=5
        if a<6:
            break
    print("hello")

If you try to do it outside a function (just in the interpreter), it does not know how to evaulate the whole thing, since it can only handle one statement at a time in the interpreter. Your while loop is such a statement, and your print stuff is such a statement, such you have two statements, but the interpreter takes only one.

like image 27
phimuemue Avatar answered Dec 10 '22 10:12

phimuemue