4

Consider this code:

with open("tmp", "w") as f:
    print(0)
print(1)

This works when saved as bug.py and run with python bug.py. But I can't copy and paste this code into a python interpreter:

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("tmp", "w") as f:
...     print(0)
... print(1)
  File "<stdin>", line 3
    print(1)
    ^
SyntaxError: invalid syntax
>>>

Where's the syntax error?

Edit: This applies more generally, as in

if False:
    pass
pass

1 Answer 1

6

You need an extra empty line to end up your with statement and input the next print statement:

>>> with open('/dev/random') as fin :
...     print(0)
...                             <<--- an empty line
0
>>> print(1)
1
>>> 
Sign up to request clarification or add additional context in comments.

2 Comments

Any loop should be closed in the interactive mode by pressing <Return> twice before any other statement.
Is there any way I could have known that? ;)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.