Why does Python 3.1 throw a SyntaxError when printing after a loop?

I try to run this snippet in the Python 3.1 console, and I get a SyntaxError:

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

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

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

+4
source share
2 answers

It works if you put all this in a function:

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

If you try to do this outside the function (only in the interpreter), she does not know how to redeem it all, since she can only process one statement at a time in the interpreter. Your while is such a statement, and your print material is such a statement, so you have two statements, but the interpreter only accepts one.

+7
source

You need to enter a blank line in the REPL to complete the current block before you can enter a new, loose line of code.

+9
source

Source: https://habr.com/ru/post/1309252/


All Articles