4

Python 2.7.8 print statement “Syntax Error: invalid syntax” in terminal(14.04) but running well on vim, why?

Following program prints the sum of squares, First I try to run this problem on terminal it is giving the "Syntax Error: invalid syntax" but when copied the same code on vim editor and run on terminal python for.py (Name of the file is for.py), It is giving no error, please explain the reason behind it.

On Running direct on terminal

Type "help", "copyright", "credits" or "license" for more information.
>>> squares= [1, 4, 9, 16]
>>> sum=0
>>> for num in squares:
...     sum+=num
... print sum

File "<stdin>", line 3
  print sum
    ^
SyntaxError: invalid syntax

On vim

$ vim for.py
squares= [1, 4, 9, 16]
sum=0
for num in squares:
   sum+=num
print sum

python for.py

output:30 #Running correctly

After suggesting by @mgilson and @ohope5, it working thanks

Type "help", "copyright", "credits" or "license" for more information.
>>> squares=[1, 4, 9, 16]
>>> sum=0
>>> for num in squares:
...     sum+=num
... 
>>> print sum
30
0

2 Answers 2

5

The REPL (read-evaluate-print-loop) can't look ahead at the next line to see if the loop ends the same way that the normal parser can. In other words, when python's normal parser parses your file, it sees the dedent and knows that the loop ends after sum+=num. When the REPL gets to the same line, it has no way of knowing if there should be another statement so it assumes that there is another statement. The way to tell the REPL that this is the terminal line of a loop (or, more generally, the end of any suite of commands) is to enter a blank line.

Sign up to request clarification or add additional context in comments.

Comments

4

The problem is that when using python interactively, you have to give an empty line after any kind of loop or function, otherwise it thinks that the next line is related to this. This means that after sum+=num you need to leave an empty line before your print statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.