pythonbook/Python 基础教程/1.9.1 E函数 匿名函数.py

11 lines
711 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 关键字lambda表示匿名函数冒号前面的n表示函数参数可以有多个参数。
#
# 匿名函数有个限制就是只能有一个表达式不用写return返回值就是该表达式的结果。
#
# 用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
#
# 有些函数在代码中只用一次,而且函数体比较简单,使用匿名函数可以减少代码量,看起来比较"优雅“
a = lambda x,y,z:x*x+y*y+z*z if x>0 and y>0 and z>0 else -x*x-y*y-z*z
# 函数名 参数:返回值
print(a(-2,-3,-4))