如何编写内联if语句用于打印? [英] How to write inline if statement for print?
问题描述
只有当布尔变量设置为 True
时,我才需要打印一些东西。所以,在看了这个后,我尝试了一个简单的例子:
I need to print some stuff only when a boolean variable is set to True
. So, after looking at this, I tried with a simple example:
>>> a = 100
>>> b = True
>>> print a if b
File "<stdin>", line 1
print a if b
^
SyntaxError: invalid syntax
如果我写打印一个if b == True
。
我在这里缺少什么?
推荐答案
Python 不如果 声明,则有一个的结尾。
Python does not have a trailing if
statement.
有两种如果在Python中
:
-
if
声明:
if condition: statement
if condition:
block
if
表达(介绍)在Python 2.5)
if
expression (introduced in Python 2.5)
expression_if_true if condition else expression_if_false
请注意,打印
和 b = a
是陈述。只有 a
部分才是表达式。所以如果你写的话
And note, that both print a
and b = a
are statements. Only the a
part is an expression. So if you write
print a if b else 0
表示
print (a if b else 0)
类似于写作时
x = a if b else 0
意味着
x = (a if b else 0)
现在如果没有 else
子句,它会打印/分配什么?打印/作业仍然存在。
Now what would it print/assign if there was no else
clause? The print/assignment is still there.
请注意,如果您不希望它在那里,您可以随时写常规 if
语句在单行上,虽然它的可读性较差,并且没有理由避免使用双行变体。
And note, that if you don't want it to be there, you can always write the regular if
statement on a single line, though it's less readable and there is really no reason to avoid the two-line variant.
这篇关于如何编写内联if语句用于打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!