首页 > 文章列表 > python如何实现条件选择

python如何实现条件选择

Python 条件选择
255 2022-08-07

1、Python 中使用 if、elif、else 来进行基础的条件选择操作:

if x < 0:
     x = 0
     print('Negative changed to zero')
 elif x == 0:
     print('Zero')
 else:
     print('More'

2、Python 同样支持 ternary conditional operator,也可以使用 Tuple 来实现类似的效果:

# test 需要返回 True 或者 False
(falseValue, trueValue)[test]
 
# 更安全的做法是进行强制判断
(falseValue, trueValue)[test == True]
 
# 或者使用 bool 类型转换函数
(falseValue, trueValue)[bool(<expression>)]

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。