不像 C++,我们在 Python 中没有?:,但我们有这个:
1[on true] if [expression] else [on false]
如果表达式为True,就执行[on true]中的语句。否则,就执行[on false]中的语句。
下面是使用它的方法:
1>>> a,b=2,3
2>>> min=a if a<b else b
3>>> min
运行结果:
12
2>>> print("Hi") if a<b else print("Bye")
1Hi
不像 C++,我们在 Python 中没有?:,但我们有这个:
1[on true] if [expression] else [on false]
如果表达式为True,就执行[on true]中的语句。否则,就执行[on false]中的语句。
下面是使用它的方法:
1>>> a,b=2,3
2>>> min=a if a<b else b
3>>> min
运行结果:
12
2>>> print("Hi") if a<b else print("Bye")
运行结果:
1Hi