当前位置: 首页 > 图灵资讯 > 行业资讯> python如何实现条件选择

python如何实现条件选择

来源:图灵python
时间: 2024-08-14 11:14:26

1、Python 中使用 if、elif、else 选择操作基本条件:

ifx<0:
x=0
print('Negativechangedtozero')
elifx==0:
print('Zero')
else:
print('More'

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

#test需要返回True或Falsese
(falseValue,trueValue)[test]

#更安全的做法是强制判断
(falseValue,trueValue)[test==True]

#或者使用bool类型转换函数
(falseValue,trueValue)[bool(<expression>)]

以上是python实现条件选择的方法,希望对大家有所帮助。更多Python学习指导:python基础教程

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