SyntaxError near “print”? [closed]

2019-01-20 17:25发布

can anybody please tell me why this is giving me syntax error in idle?

def printTwice(bruce):
    print bruce, bruce

SyntaxError: invalid syntax

2条回答
▲ chillily
2楼-- · 2019-01-20 18:01

You seem to be trying to print incorrectly.

You can use a Tuple:

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

Or you can use formatting in a string in Python ~2.7:

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

Or use a function in Python 3:

def p(bruce):
    print("{0}{1}".format(bruce, bruce))
查看更多
迷人小祖宗
3楼-- · 2019-01-20 18:04

Check the version of Python being used; the variable sys.version contains useful information.

That is invalid in Python 3.x, because print is just a normal function and thus requires parenthesis:

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

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

(The behavior in Python 2.x is different, where print was a special statement.)

查看更多
登录 后发表回答