Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error when executing line, outside loop in Python Interpreter

I was trying some stuff out in the python interpreter [3.10] and wanted to execute a for loop:

If I execute the following code on python:

>>> for i in range(4):
...     print(i, end = ': ')
... print('\n')

I get an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  File "<stdin>", line 3
    print('\n')
    ^^^^^
SyntaxError: invalid syntax

However if I execute the same code in ipython, there are no errors:

In [1]: for i in range(4):
   ...:     print(i, end = ': ')
   ...: print('\n')

Output:

0: 1: 2: 3:

>Solution :

You must only give the python interpreter one statement at a time.

This might be a code block, in which case it will wait for you to dedent before executing.

But including the second statement print('\n') is invalid input.

On the other hand, in a Python program, executed from a file, you can have multiple statements. This accounts for the difference in behavior.

In short: provide an extra return before print('\n') so the interpreter can execute your first statement before you move on to the next.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading