Python SyntaxError:语法无效end =''

时间:2013-11-19 14:04:53

标签: python python-3.x

我正在研究“Head First Python”一书,我遇到了这段代码的问题:

data = open('sketch.txt')

for each_line in data:
    (role, line_spoken) = each_line.split(':')
    print(role, end='')
    print(' said: ', end='')
    print(line_spoken, end='')

data.close()

错误:

  File "Aula 3.py", line 12
      print(role, end='')
               ^
SyntaxError: invalid syntax

sketch.txt:

Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!

我有两天时间试图找出代码无效的原因。错误始终显示在“end =''”中。

7 个答案:

答案 0 :(得分:24)

看起来你正在使用Python 2.x,而不是Python 3.x。

检查你的python版本:

>>> import sys
>>> sys.version
'2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)]'
>>> print(1, end='')
  File "<stdin>", line 1
    print(1, end='')
                ^
SyntaxError: invalid syntax

在Python 3.x中,它不应该引发语法错误:

>>> import sys
>>> sys.version
'3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)]'
>>> print(1, end='')
1>>>

答案 1 :(得分:6)

>>> import sys
>>> print(sys.version)
2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)]
>>> from __future__ import print_function
>>> print(1, end=',')
1,

答案 2 :(得分:2)

如果您从命令行运行它,您可能只需要使用python3命令而不仅仅是python命令,例如:

python3 MyFile.py

答案 3 :(得分:1)

我遇到了与Eclipse和IntelliJ IDEA相同的问题,只是在Eclipse上解决了它。使用PyDev的首选项 - 解释器添加了Python 3.6,但我的Mac OS X上的原生Python高于Python 3.6的新安装。所以简单地在解释器中向上移动3.6解决了我的问题。

End result

答案 4 :(得分:1)

尽管将3.x设置为默认值,但在同时使用Python 2.7和3.x时出现相同的问题。 因为我的Python 3.x版本中的PyInstaller被删除(不知道为什么),所以使用了另一个。 重新安装PyInstaller解决了该问题。 请注意,PyInstaller在其输出的开头显示了使用的版本:

61 INFO: PyInstaller: 3.5
61 INFO: Python: 2.7.16

答案 5 :(得分:0)

当你使用eclipse编辑器时,只需键入这样的,

from __future__ import print_function

for i in range(0,5):
    for j in range(0,i):
        print(j, end='')
    print()

答案 6 :(得分:-1)

如果您确定已安装Python 3+,请在.py文件中键入此第一行:

#!/usr/bin/python3.x  <<----- where x is your installed version. 

示例:我使用以下代码启动文件:#!/usr/bin/python3.5 (因为我安装了3.5)

相关问题