1、定义函数
def 函数名(参数列表):
函数体
return 返回值
求长方形的面积
def area(width,height):
s= width *height
return s
2、函数参数
1、使用关键字参数调用函数
先定义函数
def print_area(width,height):
area = width *height
print('{0} x {1}长方形的面积是:{2}'.format(width,height,area))
调用函数方式:
①没有采用关键字参数调用函数
print_area(320,480)
②采用关键字调用函数
print_area(width = 320,height = 480)
③采用关键字调用函数
print_area(320,height = 480)
④采用关键字调用函数
print_area(height = 480,width = 320)
2、函数默认值
在定义函数的时候可以为参数设置一个默认值,调用函数时可以忽略该参数。
def drink(name = ‘咖啡’):
return ‘我喜欢喝{0}’.format(name)
在调用的时候,如果调用者没有传递参数,则使用默认值。
3、可变参数
定义:函数中的参数个数可以变化,它可以接受不确定数量的参数。
方式:有两种,在参数前加*或**形式。
①、*可变参数在函数中被组装成一个元组
def sum(*numbers , multiple = 1):
total = 0
for number in numbers:
total += number
return total * multiple
print(sum(100,20))
print(sum(30,20,multiple=2))
double_tuple = (50,60)
print(sum(20,*double_tuple))#拆解元组中的参数值
②、**可变参数在函数中被组装成一个字典
def show_info(sep = ':' , **info):
print('------------info---------')
for key,value in info.items():
print('{0} {2} {1}'.format(key,value,sep))
stu_dict={'name':'tom','age':23}
print(show_info(**stu_dict))
3、函数返回值
1、无返回值
有的函数只是为了处理某个过程,此时可以将函数设置为无返回值。实际上返回None.
def show_info(sep = ':' , **info):
print('------------info---------')
for key,value in info.items():
print('{0} {2} {1}'.format(key,value,sep))
return #返回None或省略return
2、有返回值
①、单一返回值:
def sum(*numbers,multiple=1):
if len(numbers) ==0:
return None
total = 0
for number in numbers:
total += number
return total * multiple
print(sum(30,80))
print(sum(multiple=2))
如果长度为0,则无需进行下面的运算。
②、多返回值
Ⅰ、使用元组接收多个返回值。元组可接收多个值,且不可变,使用安全。
def position(t,speed):
posx = speed[0]*t
posy = speed[1]*t
return (posx,posy)
move = position(60,(10,-5))
print('物体位移:({0},{1})'.format(move[0],move[1]))
4、函数变量作用域
全局变量和局部变量
①、全局变量
x = 20
def print_value():
print('函数中的x = {0}'.format(x))
print_value()
print('全局变量x = {0}'.format(x))
②、局部变量
x = 20
def print_value():
x = 10
print('函数中的x = {0}'.format(x))
print_value()
print('全局变量x = {0}'.format(x))
程序输出结果为:
函数中的x = 10
全局变量x = 20
③、在局部定义全局变量
x = 20
def print_value():
global x
x = 10
print('函数中的x = {0}'.format(x))
print_value()
print('全局变量x = {0}'.format(x))
程序输出结果为:
函数中的x = 10
全局变量x = 10
5、生成器
在函数中经常使用return关键字返回数据,但不能返回可迭代的数据。
此时,要用yield关键字返回可迭代的数据:比如平方数列。
不用yield时的代码是这样的:
def area(num):
lst = []
for i in range(1,num+1):
lst.append(i*i)
return lst
for i in area(5):
print(i,end=' ')
使用yield关键字,代码是这样的
def area(num):
for i in range(1,num+1):
yield i * i
for i in area(5):
print(i ,end=' ')
**注:**可迭代对象可以使用__next__()
方法获得元素。
比如:
def square(num):
for i in range(1,num+1):
yield i*i
n = square(5)
print(n.__next__())
print(n.__next__())
print(n.__next__())
print(n.__next__())
print(n.__next__())
程序输出结果为:
1
4
9
16
25