主要内容
1.函数基本语法及特性
2.参数与局部变
3.返回值 4.递归
5.名函数 6.函数式编程介绍
7.阶函数 8.内置函数
函数基本语法及特性
定义
数学函数定义:一般的,在一个变化过程中,如果有两个变量x和y,并且对于x的每一 个确定的值,y都有唯一确定的值与其对应,那么我们就把x称为自变量,把y称为因变 量,y是x的函数。自变量x的取值范围叫做这个函数的定义域。
但编程中的「函数」概念,与数学中的函数是有很 同的 函数是逻辑结构化和过程化的一种编程方法
函数的优点
减少重复代码
使程序变的可扩展
使程序变得易维护
函数与过程
定义函数
def fun1(): #函数名称
"The function decription" print("in the func1") return 0 #返回值
定义过程
def fun2():"The progress decription"print("in the func2")
函数与过程 过程就是没有返回值的函数 但是在python中,过程会隐式默认返回none,所以在python中即便是过程也可以算作函数。
def fun1(): "The function decription" print("in the func1") return 0def fun2(): "The progress decription" print("in the func2")x=fun1()y=fun2()print("from func1 return is %s" %x)print("from func2 return is %s" %y)
结果为:
in the func1in the func2from func1 return is 0from func2 return is None
返回值
要想获取函数的执 结果,就可以 return语 把结果返回。
函数在执 过程中只要遇到return语 ,就会停 执 并返回结果,所以也可以 解为 return 语 代表着函数的结束,如果未在函数中指定return,那这个函数的返回值为None。
接受返回值
赋予变量,例如:
def test(): print('in the test') return 0x=test()
返回什么样的变量值
return 个数没有固定,return的类型没有固定。 例如:
def test1(): print('in the test1')def test2(): print('in the test2') return 0def test3(): print('in the test3') return 1,'hello',['alex','wupeiqi'],{'name':'alex'}def test4(): print('in the test4') return test2x=test1()y=test2()z=test3()u=test4()print(x)print(y)print(z)print(u)
结果是:
in the test1
in the test2
in the test3
in the test4
None
0
(1, 'hello', ['alex', 'wupeiqi'], {'name': 'alex'})
<function test2 at 0x102439488>
返回值数=0:返回None 没有return
返回值数=1:返回object return一个值,python 基本所有的数据类型都是对象。
返回值数>1:返回tuple, return多个值。
返回可以返回函数:return test2会将test2的内存地址返回。
为什么要有返回值?
新闻热点
疑难解答