函数

def test1():
print("Hello,world!")
return 0 #结束函数,并返回0,该值可传递给变量。当不写return时,返回:None

x = test1()
print(x)

def test2():
print("Hello,world!")
return 1,'hello',['aa','bb'],{'name':'human'}

y = test2()
print(y)

###########################################
def test(x,y,z):
print(x)
print(y)
print(z)

test(100,z=3,y=2) #位置参数必须在关键字参数的前面!

###########################################
def test(*args): #星号表示可接受N多个不固定数量的实参
print(args)

test(1,2,3,4,5,6)
test([1,2,3,4,5,6])
test(*[1,2,3,4,5,6])

def test(x,*args): #args名字可以改为其它名称。
print(x)
print(args)

test(1)
test(1,2,3,4,5,6)

###########################################
def test(**kwargs): #接受字典作为实参。把N个关键字参数转换成字典的方式
print(kwargs)

test(name='hehe',sex='man',age=28) #数量不限
test(**{'name':'hehe','sex':'man','age':8})

def test(name,**kwargs):
print(name)
print(kwargs)

test('human',sex='man',age=28)

def test(name,age=18,*args,**kwargs): #**kwargs:接受N个关键字参数,转换成字典方式
print(name)
print(age)
print(args)
print(kwargs)

test('human',age=28,sex='man',hobby='tesla')

#函数内定义的变量,只在函数体内生效。称为局部变量。
#在程序一开始定义的变量称为全局变量。全局变量作用域是整个程序。
#当全局变量与局部变量同名时,在定义局部变量的函数体内,局部变量起作用,在其它地方全局变量起作用

def test():
global school #将局部变量声明为全局变量。但不建议这么做。不利于程序调试排错。作死行为
school = 'oldboy'

test()

###########################################
#递归:如果一个函数在内部调用自身本身,这个函数就是递归函数
#最大递归层数:999(避免层数过多导致机器资源消耗完)
#每次进入更深一层递归时,问题规模相比上次递归都应有所减少
#递归效率不高,递归层次过多导致栈溢出
#要明确递归的结束条件
#“问题规模”每递归一次都应该比上一次的问题规模有所减少

#如果一个函数A可以接收另一个函数作为参数,这种函数A称为高阶函数

###########################################
#高阶函数:
#1.把一个函数名当作实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
#2.返回值中包含函数名(不修改函数的调用方式)

def bar():
print('in the bar')

def test(func):
print(func) #将显示bar函数的内存地址
func()

test(bar) #把一个函数名当作实参传给另外一个函数



posted @ 2017-10-25 10:13  浆糊jun  阅读(159)  评论(0编辑  收藏  举报