Python Forum

Full Version: SyntaxError when i used interpreter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
Did you copy and paste this into IDLE? If so, "f.close()" should have been after the loop had already been processed.
(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.…
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.
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().
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.
Ohhhhhhhh!
Thank you,stullis! That was the reason
One time one statement!