python 4 函數(shù)與模塊
2023-02-27 16:13 作者:戎碼關(guān)山 | 我要投稿
函數(shù)
#打印乘法口訣
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是實參
#默認參數(shù)
def machine(money = 18,food = '套餐'):#注意:默認參數(shù)必須從右往左進行賦值
? ?print('一份 %d 元 %s'%(money,food))
machine(1,'jz')
machine()
#關(guān)鍵參數(shù),好處是可以不按順序賦值
def machine(money = 18,food = '套餐',other = ''):#注意:默認參數(shù)必須從右往左進行賦值
? ?if not other:
? ? ? ?print('一份 %d 元 %s'%(money,food))
? ?else:
? ? ? ?print('一份 %d 元 %s 外加 %s'%(money,food,other))
machine(12,other='可樂')
#冗余參數(shù)處理
def machine(money = 18,food = '套餐',*other):#設(shè)置可變長的參數(shù)
? ?if not other:
? ? ? ?print('一份 %d 元 %s'%(money,food))
? ?else:
? ? ? ?print('一份 %d 元 %s 外加 %s'%(money,food,other))
machine(12,"kele",'薯條','蘇打水')
#內(nèi)建函數(shù)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)
#內(nèi)建函數(shù)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))
#模塊是包含了很多函數(shù)或者類的一個腳本,而包可以理解為是一個包含了很多模塊的一個目錄,該文件夾下必須存在__init__.py文件
標簽: