我需要打印一些东西,只有当布尔变量设置为True。所以,在看完这个之后,我尝试了一个简单的例子:
>>> a = 100
>>> b = True
>>> print a if b
File "<stdin>", line 1
print a if b
^
SyntaxError: invalid syntax
同样的,如果我写print a if b==True。
我错过了什么?
我需要打印一些东西,只有当布尔变量设置为True。所以,在看完这个之后,我尝试了一个简单的例子:
>>> a = 100
>>> b = True
>>> print a if b
File "<stdin>", line 1
print a if b
^
SyntaxError: invalid syntax
同样的,如果我写print a if b==True。
我错过了什么?
当前回答
你总是需要在内联if中使用else:
a = 1 if b else 0
但更简单的方法是a = int(b)
其他回答
你为什么不简单地写:
if b:
print a
else:
print 'b is false'
试试这个。这可能对你有帮助
a=100
b=True
if b:
print a
对于你的情况,这是有效的:
a = b or 0
编辑:这是如何工作的?
在问题中
b = True
所以评估
b or 0
结果
True
它被赋值给a。
如果b == False?, b或0将求值为第二个操作数0,该操作数将赋值给a。
你可以使用:
print (1==2 and "only if condition true" or "in case condition is false")
你还可以继续这样说:
print (1==2 and "aa" or ((2==3) and "bb" or "cc"))
现实世界的例子:
>>> print ("%d item%s found." % (count, (count!=1 and 's' or '')))
1 item found.
>>> count = 2
>>> print ("%d item%s found." % (count, (count!=1 and 's' or '')))
2 items found.
你可以这样写一个内联三元运算符:
sure = True
# inline operator
is_true = 'yes' if sure else 'no'
# print the outcome
print(is_true)