python 的三元操作符


条件表达式(三元操作符)     

1.有了这个三元操作符的条件表达式,你可以使用一条语句来完成下面的条件判断和赋值操作;

x,y=4,5

if x<y:

  temp = x

else:

  temp = y

列子可以改进为

temp = x if x<y else y

print(temp)   

 

例子2         比较三个数中比较小的一个:

x,y,z=1,2,3

if x<y:

    temp=x

else:

    temp=y

if temp<z:

    print(temp)

else:

    temp=z

 

    print(temp)

 

可以改进为:

x ,y,z =1,2,3
temp = (x if x < y else y)

temp = (z if temp> z else temp)

print(temp)

例子3         比较三个数中最大的一个:

 

x,y,z=1,2,3

if x>y:

    temp=x

else:

    temp=y

if temp>z:

    print(temp)

else:

    temp=z

 

    print(temp)

 

例子可以改进为:

a,b,c = 1,2,3

max = (a if a > b else b)

max = (c if max< c else c)

print(max)

以上就是三元操作符的基本内容了!(喜欢就关注我吧!)

 

                                                                


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM