gpt4 book ai didi

Python 语法错误 : invalid syntax end =''

转载 作者:IT老高 更新时间:2023-10-28 20:59:51 30 4
gpt4 key购买 nike

我正在研究“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 =''”中。

最佳答案

您似乎使用的是 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>>>

关于Python 语法错误 : invalid syntax end ='' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20073639/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com