【问题标题】:Python syntax error (in the interpreter) after a for loopfor 循环后的 Python 语法错误(在解释器中)
【发布时间】:2012-08-30 01:59:43
【问题描述】:

我正在从控制台运行一些 python 代码(粘贴),并得到了意想不到的结果。代码如下所示:

parentfound = False
structfound = False
instruct = False
wordlist = []
fileHandle = open('cont.h')
for line in fileHandle:
    if line is "":
        print "skipping blank line"
        continue
    if "}" in line:
        instruct = False
        index = line.index("}")
        wordlist.append(word)
    pass          
try:
    print wordlist
except Exception as e:
    print str(e)

在for循环之后,我想打印wordlist。无论我做什么,我都不能在 for 循环之外包含任何内容。这是我收到的错误:

...     if "}" in line:
...         instruct = False
...         index = line.index("}")
...         wordlist.append(word)
...     pass          
... try:
  File "<stdin>", line 10
    try:
      ^
SyntaxError: invalid syntax

无论我是手动将代码输入终端还是将其粘贴到终端中,都会出现这种情况。如果您能提供任何帮助,我将不胜感激。谢谢!

【问题讨论】:

  • 它对我有用。您是否可能有缩进错误,在某处有多余的空格或制表符? (您的代码中存在一些逻辑错误,但至少它可以运行。)
  • word 中的wordlist.append(word) 是什么?
  • 代码不完整——我尽可能地减少了,但仍然出现错误,这样更容易找到问题的根源

标签: python file syntax syntax-error


【解决方案1】:

REPL 中的... 提示意味着它还没有完成前一个块。您需要先在空行上按 Enter 来终止它。

【讨论】:

  • 谢谢。我会试一试。如果我将它包含在 python 文件中,而不是将它输入到解释器中,我还会遇到这个错误吗?
  • 没有。这种行为是 REPL 特有的。
  • 感谢您的快速回复——这让我发疯了。时间一到,我会立即接受答案!
  • @IgnacioVazquez-Abrams 这也解决了我的问题 - 谢谢。这种行为(包括... 提示)是否记录在某处?我一定错过了。
  • 侧边栏:另一种解决方案是使用 IPython,它似乎没有这些细微差别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多