Python 中的内联 if...else 语句
Manav Narula
2023年10月10日

if ... else
语句在许多编程语言中经常用于评估条件。
Python 有一个内联的 if ... else
语句,它允许在一行中使用一个紧凑的 if ... else
语句。这样的内联语句是有限制的,只有当多个 if ... else
被仔细级联时,才能包含多个 if ... else
。但是,它们必须包含 else
子句;否则,它将无法正常工作。
这样的语句可以提高代码的可读性,使代码更短更干净,并且可以在赋值或其他函数时使用。
在下面的代码中,我们将在根据另一个变量的值向一个变量赋值时使用它。
b = 5
a = 1 if b > 2 else 2
print(a)
输出:
1
请注意,由于它们的相似性,此类内联 if ... else
语句被认为是 Python 中的三元操作符。
我们也可以将内联 if ... else
语句与其他函数(如 print()
)一起使用,以根据条件显示一些东西。
a = 0
b = 2
print(a if a != 0 else b)
输出:
2
我们可以在内联语句中映射多个 if ... else
条件。例如,我们可以在内联语句中映射多个 if ... else
条件。
b = 5
a = 1 if b == 2 else (2 if b > 3 else 3)
print(a)
输出:
2
elif
条件不能用于内联 if ... else
语句。
作者: Manav Narula
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn