在一行中写if语句

Νικ*_*γος 1 printing if-statement python-3.x

虽然以下陈述是正确的:

print( "10 is greater than 5" ) if 10>5 else print( "nothing here " )
Run Code Online (Sandbox Code Playgroud)

删除其他原因错误 SyntaxError: unexpected EOF while parsing

print( "10 is greater than 5" ) if 10>5
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Mur*_*nik 6

print是一个函数,它只需要一个值.换句话说,您需要一次调用print,并表示作为在线人员所需的值if:

print ("10 is greater than 5" if 10 > 5 else "nothing here")
Run Code Online (Sandbox Code Playgroud)

  • 仅在python 2中.这个问题要求3 (2认同)