Python Forum
SyntaxError when i used interpreter - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: SyntaxError when i used interpreter (/thread-15413.html)



SyntaxError when i used interpreter - hydor - Jan-16-2019

Hi.
I'm just a beginner, and I have a problem that I couldn't understand the reason.

f = open ("C:/doit/newfile.txt", 'w')
for i in range(1,11):
    data = "%d line. \n" % i
    f.write(data)
f.close()
I was practising file input and output.
when I tried to run on windows command prompt, it was successful.
On the other hand, on python interpreter (Python3.7.2), it had a syntax error like below.

>>> f = open ("C:/doit/newfile.txt", 'w')
>>> for i in range(1,11):
...     data = "%d line. \n" % i
...     f.write(data)
... f.close()
  File "<stdin>", line 4
    f.close()
    ^
SyntaxError: invalid syntax
Please let me know the reason.


RE: SyntaxError when i used interpreter - stullis - Jan-16-2019

Did you copy and paste this into IDLE? If so, "f.close()" should have been after the loop had already been processed.


RE: SyntaxError when i used interpreter - hydor - Jan-16-2019

(Jan-16-2019, 05:44 PM)stullis Wrote: Did you copy and paste this into IDLE? If so, "f.close()" should have been after the loop had already been processed.
Could you please explain it in more detail?
What was the difference? The statement was the same.…


RE: SyntaxError when i used interpreter - gontajones - Jan-16-2019

You need to add one more ENTER after f.write(data).
>>> f = open ("C:/doit/newfile.txt", 'w')
>>> for i in range(1,11):
...     data = "%d line. \n" % i
...     f.write(data)
<<ENTER AGAIN HERE>>
>>> f.close()
Doing this the interpreter will "close" the for loop.


RE: SyntaxError when i used interpreter - ichabod801 - Jan-16-2019

What stullis is saying is that you should have entered a blank line after entering the loop. That would let the loop process. Then you enter the line with f.close().


RE: SyntaxError when i used interpreter - stullis - Jan-16-2019

The interpreter can only accept one statement at a time. The loop is one statement and the method call outside the loop is a second one. If you attempt inputting them simultaneously, the interpreter will give a syntax error because it believes the method call is intended to be part of the loop and the indentation would be wrong.

You could save the whole script as a *.py file and run it with IDLE with no problems instead.


RE: SyntaxError when i used interpreter - hydor - Jan-16-2019

Ohhhhhhhh!
Thank you,stullis! That was the reason
One time one statement!