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)

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

                                                                

原文地址:https://www.cnblogs.com/love2000/p/11529607.html