给定 python 代码的打印语句语法错误的原因是什么

What is reason for syntax error of print statement of given python code

xString = input("Enter a number: ")
x = int(xString)
yString = input("Enter a second number: ")
y = int(yString)
print('The sum of ', x, ' and ', y, ' is ', x+y, '.', sep='')

在执行上面的代码时,解释器抛出语法错误,说语法错误如下。

 print(?The sum of ?, x, ? and ?, y, ? is ?, sum, ?.?, sep=??)

语法错误:语法无效

这是因为像 这样古怪的引号字符。将它们更改为 ' 个字符,您应该没有任何问题。

首先,将 替换为 '

其次,您可能需要再补充一句:from __future__ import print_function

打印语句中使用的单引号是',ascii值为39。

>>> ord("'")
39

问题中打印语句中使用的 不是引号 ' 而是 RIGHT SINGLE QUOTATION MARK' (U+2019)

>>> u"’"
u'\u2019'

因为您正在使用 python 2,要在打印语句中使用 sep 您需要 从未来导入功能

from __future__ import print_function
print('The sum of ', x, ' and ', y, ' is ', x+y, '.', sep='')