考虑这个代码:
with open("tmp", "w") as f:
print(0)
print(1)
这在另存为
bug.py
时有效并使用 python bug.py
运行.但我无法将此代码复制并粘贴到 python 解释器中: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
>>>
语法错误在哪里?
编辑:这更普遍地适用,如
if False:
pass
pass
最佳答案
你需要一个额外的空行来结束你的 with
语句并输入下一个 print
陈述:
>>> with open('/dev/random') as fin :
... print(0)
... <<--- an empty line
0
>>> print(1)
1
>>>
关于python - 为什么我的代码在 .py 文件中运行时可以工作,但在 Python 解释器中返回 SyntaxError ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61586186/