0

谁能告诉我为什么这给我空闲时的语法错误?

def printTwice(bruce):
    print bruce, bruce

SyntaxError:无效的语法

4

2 回答 2

5

检查正在使用的 Python 版本;该变量sys.version包含有用的信息。

这在 Python 3.x 中是无效的,因为print只是一个普通函数,因此需要括号:

# valid Python 3.x syntax ..
def x(bruce): print(bruce, bruce)
x("chin")

# .. but perhaps "cleaner"
def x(bruce):
    print(bruce, bruce)

(Python 2.x 中的行为有所不同,其中print有一个特殊语句。)

于 2012-09-26T01:54:56.557 回答
3

您似乎试图打印不正确。

您可以使用元组:

def p(bruce):
    print (bruce, bruce) # print((bruce, bruce)) should give a tuple in python 3.x

或者您可以在 Python ~2.7 中的字符串中使用格式设置:

def p(bruce):
    print "{0}{1}".format(bruce, bruce)

或者使用 Python 3 中的函数:

def p(bruce):
    print("{0}{1}".format(bruce, bruce))
于 2012-09-26T02:01:10.573 回答