Python:三元运算符语法

2024-04-20 07:59:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在程序中使用三元条件,如下所示:

c = 12
(print c) if (c == 10) else (print 'c is not 10')

但是,这会引发语法错误。这里怎么了?在


Tags: 程序ifisnot条件elseprint语法错误
2条回答

你应该做print(c)而不是{}

你可以这样做:

print c if c == 10 else 'c is not 10'

括号是不必要的,必须以“print”开头;Python不能像Perl那样使整个命令成为条件。在

在Python中没有Perl的等价物:

^{pr2}$

相关问题 更多 >