python 4 函数与模块
函数
#打印乘法口诀
def fun99():
for i in range(1,3):
for j in range(1,i+1):
print(j,'*',i,'=',i*j,'\t',end = ' ')
print('\n')
fun99()
#形参,实参
def fun99(x):#形参
for i in range(1,x+1):
for j in range(1,i+1):
print(j,'*',i,'=',i*j,'\t',end = ' ')
print('\n')
fun99(9)#9是实参
#默认参数
def machine(money = 18,food = '套餐'):#注意:默认参数必须从右往左进行赋值
print('一份 %d 元 %s'%(money,food))
machine(1,'jz')
machine()
#关键参数,好处是可以不按顺序赋值
def machine(money = 18,food = '套餐',other = ''):#注意:默认参数必须从右往左进行赋值
if not other:
print('一份 %d 元 %s'%(money,food))
else:
print('一份 %d 元 %s 外加 %s'%(money,food,other))
machine(12,other='可乐')
#冗余参数处理
def machine(money = 18,food = '套餐',*other):#设置可变长的参数
if not other:
print('一份 %d 元 %s'%(money,food))
else:
print('一份 %d 元 %s 外加 %s'%(money,food,other))
machine(12,"kele",'薯条','苏打水')
#内建函数fliter
def ou(x):
if x%2==0:
return True
l = [1,2,3,4,5]
re = filter(ou,l)
for i in re:
print(i)
#内建函数map
def ad(x,y):
return x+y
l1 = [1,2,3]
l2 = [2,3,4,5]
re = map(ad,l1,l2)
for i in re:
print(i)
#lambda
re = filter(lambda x:x%2==0,l1)
for i in re:
print(i)
re= map(lambda x,y:x+y,l1,l2)
for i in re:
print(i)
模块
import function #1
form function import * #1
print(function.ad(1,2))
from function import ad #3
print(ad(1,3))
#模块是包含了很多函数或者类的一个脚本,而包可以理解为是一个包含了很多模块的一个目录,该文件夹下必须存在__init__.py文件