自定義函數(shù)及調(diào)用
創(chuàng)建一個(gè)專(zhuān)門(mén)存放自定義函數(shù)的文件夾 D:\python\customize
構(gòu)建一個(gè)簡(jiǎn)單的函數(shù)
def greet_user(): # 關(guān)鍵詞 def 開(kāi)頭,后接定義的函數(shù)名肺然,括號(hào)必不可少辉饱,最后以冒號(hào)結(jié)尾
'''顯示簡(jiǎn)單的問(wèn)候語(yǔ)''' # 注釋用三個(gè)引號(hào)括起
print('Hello!') # 單引號(hào)雙引號(hào)都可以
將函數(shù)保存到 customize 文件夾中已骇,命名為greet.py
調(diào)用自定義的函數(shù)
import sys
sys.path.append(r"D:\python\customize") # 設(shè)置自定義的路徑
import greet # 調(diào)用自定義函數(shù)greet.py的文件名
greet.greet_user() # 調(diào)用函數(shù)方式
參數(shù)的位置
函數(shù)調(diào)用要根據(jù)定義時(shí)參數(shù)變量的位置
def difference(x,y):
diff = x - y
print(diff) # diff作為一個(gè)變量不用加雙引號(hào)颤陶,加了雙引號(hào)就會(huì)打印diff而不會(huì)打印計(jì)算的結(jié)果
difference(3,5)
difference(5,3)
根據(jù)關(guān)鍵詞調(diào)用可不按照位置來(lái)
def difference(x,y):
diff = x - y
print(diff)
difference(y=3,x=5)
默認(rèn)值
使用默認(rèn)值時(shí)臀栈,先列出沒(méi)有默認(rèn)值的參數(shù)娃圆。再列出有默認(rèn)值的參數(shù)
def difference(x,y=2):
diff = x-y
print(diff)
difference(5)
difference(5,3)
參數(shù)可選
def difference(x,y,z=''):
if z: # z 存在的時(shí)候
diff = x-y+z
else:
diff = x+y
print(diff)
difference(5,3)
difference(5,3,1)
返回值
在函數(shù)中玫锋,可使用 return 語(yǔ)句將值返回到調(diào)用函數(shù)的代碼行。返回值讓你能夠?qū)⒊绦虻拇蟛糠址敝毓ぷ饕频胶瘮?shù)中去完成讼呢,從而簡(jiǎn)化主程序
def difference(x,y):
diff = x-y
return diff
z = difference(3,5)
print(z)
函數(shù)與列表
傳遞列表
def greet_users(names):
for name in names:
msg = "Hello, " + name.title() + "!" # title返回"標(biāo)題化"的字符串,就是說(shuō)所有單詞都是以大寫(xiě)開(kāi)始撩鹿,其余字母均為小寫(xiě)
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
修改列表
def print_objects(unprinted_objects, completed_objects):
while unprinted_objects: # 當(dāng)unprinted_objects列表有值的時(shí)候執(zhí)行下列指令
current = unprinted_objects.pop() # 刪除unprinted_objects的最后一個(gè)元素并將該元素賦值給current
print("Printing object: " + current) #打印刪除的元素
completed_objects.append(current) # 在completed_objects列表末尾添加current
def show_completed(completed_objects):
print("\nThe following objects have been printed:")
for completed_object in completed_objects:
print(completed_object)
unprinted_objects = ["A","b","C"]
completed_objects = []
print_objects(unprinted_objects, completed_objects)
show_completed(completed_objects)
禁止修改列表
上述修改是在unprinted_objects
列表里面直接刪除,執(zhí)行完函數(shù)之后悦屏,該列表沒(méi)有元素變?yōu)榭樟斜斫诼伲蚝瘮?shù)傳遞列表的副本可避免這個(gè)問(wèn)題。unprinted_objects[:]
即為unprinted_objects
的副本
調(diào)用上述函數(shù)時(shí)可以用
print_objects(unprinted_objects[:], completed_objects)
任意數(shù)量的實(shí)參
傳遞任意數(shù)量的實(shí)參
當(dāng)不知道函數(shù)需要傳遞多少個(gè)實(shí)參的時(shí)候础爬,可以用*
加形參來(lái)表示
如下甫贯,*words
表示創(chuàng)建一個(gè)名為words
的空元組
def print_words(*words):
print(words)
print_words('a')
print_words('apple','grape')
結(jié)合使用位置實(shí)參和任意數(shù)量實(shí)參
def print_words(type,*examples):
print('type: '+type)
for example in examples:
print(example)
print_words('n','noun','group')
print_words('v','ask','do','can')
使用任意數(shù)量的關(guān)鍵字實(shí)參
**
加形參創(chuàng)建一個(gè)字典以使函數(shù)接受任意的鍵值對(duì)
def user_profile(name,nation,**user_info):
profile = {}
profile['name'] = name
profile['nationality'] = nation
for key,value in user_info.items():
profile[key] = value
return profile
user = user_profile('Jenny','America',gender='woman',age=25)
print(user)
將函數(shù)存儲(chǔ)在模塊中
模塊是擴(kuò)展名為.py
的文件,包含要導(dǎo)入到程序中的代碼看蚜。
在D:\python_test
目錄下創(chuàng)建一個(gè)存放長(zhǎng)方形周長(zhǎng)和面積計(jì)算公式的py
文件叫搁,內(nèi)容如下,記為rectangle_functions.py
供炎,該文件即為一個(gè)模塊
def rectangle_C(a,b):
c=(a+b)*2
return c
def rectangle_S(a,b):
s=a*b
return s
導(dǎo)入整個(gè)模塊
在rectangle_functions.py
所在的目錄中創(chuàng)建另一個(gè)名為rectangle.py
的文件渴逻,內(nèi)容如下
import rectangle_functions
C=rectangle_functions.rectangle_C(4,5)
S=rectangle_functions.rectangle_S(4,5)
print('長(zhǎng)度為4,寬度為5的長(zhǎng)方形')
print('周長(zhǎng)為'+str(C)+'音诫,面積為'+str(S))
調(diào)用rectangle
import sys
sys.path.append(r"D:\python_test")
import rectangle
# 導(dǎo)入特定的的函數(shù)
from rectangle_functions import rectangle_C
# 導(dǎo)入全部函數(shù)
from rectangle_functions import *
使用 as 指定別名
如果要導(dǎo)入的函數(shù)的名稱(chēng)可能與程序中現(xiàn)有的名稱(chēng)沖突裸卫,或者函數(shù)的名稱(chēng)太長(zhǎng),可指定簡(jiǎn)短而獨(dú)一無(wú)二的別名
# 使用 as 給模塊指定別名
import rectangle_functions as rf
# 調(diào)用方式
C=rf.rectangle_C(4,5)
# 使用 as 給函數(shù)指定別名
from rectangle_functions import rectangle_C as c
# 調(diào)用方式
C=c(4,5)
參考書(shū)目:Python編程從入門(mén)到實(shí)踐 - Eric Matthes 著纽竣,袁國(guó)忠 譯