在阅读python大神写的程序时,遇到了以下代码,乍一看没看懂,但经过测试发现非常简单。
alpha_y_tmp = 60 if alpha_y is None else alpha_y
上面的代码是一个更高级和简洁的写法,其实与下面的代码等价:
if alpha_y is None:
alpha_y_tmp = 60
else:
alpha_y_tmp = alpha_y
这两段代码的意思是一样的,即:如果alpha_y
为None
时,alpha_y_tmp = 60
;否则alpha_y_tmp = alpha_y
def test(alpha_y=None):
alpha_y_tmp = 60 if alpha_y is None else alpha_y
print(alpha_y_tmp)
test(alpha_y=5)
代码解释:
1、首先定义一个名叫test
的函数,传入的关键字参数为alpha_y=None
2、如果alpha_y
为None
时,alpha_y_tmp = 60
;否则alpha_y_tmp = alpha_y
3、打印alpha_y_tmp
的结果
4、调用test函数,因为传入的关键字参数为alpha_y=5,所以结果为alpha_y_tmp=5
5、当调用test函数时,传入的关键字参数为alpha_y=None,则结果为alpha_y_tmp=60
over!!