三元表达式
普通的if else语句如下:
y=10
if y<0:
print('this is a negative number .')
else:
print('this is a nonegative number .')
输出:this is a nonegative number .
三元式使用:
y=10
print('this is a negative numbery' if y < 0 else 'this is a nonegative number')
输出:this is a nonegative number
同样三元式也可以用来赋值:
y=10
x=1 if y >0 else -1
print (x)
输出:1
感受下三元式的一行代码的实用性,可谓是简洁大方,如果在特定的业务下编写代码,我想使用起来更是节省了很多行代码。