我需要打印一些东西,只有当布尔变量设置为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。
我错过了什么?
当前回答
'else'语句是强制的。你可以这样做:
>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>>
编辑:
或者,根据你的需要,你可以尝试:
>>> if b: print(a)
其他回答
这可以通过字符串格式化来实现。它可以使用%符号以及.format()和f-strings(3.6新增)
print '%s' % (a if b else "")
or
print '{}'.format(a if b else "")
or
print(f'{a if b else ""}')
'else'语句是强制的。你可以这样做:
>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>>
编辑:
或者,根据你的需要,你可以尝试:
>>> if b: print(a)
你总是需要在内联if中使用else:
a = 1 if b else 0
但更简单的方法是a = int(b)
因为2.5你可以使用C 's ' ' ?"三元条件运算符,语法为:
[on_true] if [expression] else [on_false]
所以你的例子很好,但你必须简单地添加其他,比如:
print a if b else ''
你只是把事情复杂化了。
if b:
print a