一個簡單的函數
先看一個簡單的函數
def say_hello(): '''打印hello''' print("Hello!") say_hello() #運行結果 Hello!
def為函數的關鍵字,say_hello為你定義的函數的名稱,還可能在括號內指出函數為完成其任務需要什么樣的信息,即便括號是空的,也是必不可少的,最后以冒號結尾。
向函數傳遞信息
def say_hello(name): '''打印hello''' print("Hello! " + name) say_hello('Frank') #運行結果 Hello! Frank
這里在括號里面加了一個變量name,然后將'Frank'傳遞給了name,輸出。
實參和形參
在函數say_hello的定義中,變量name是一個形參——函數完成其工作所需的一項信息。在代碼say_hello('Frank')中,其'Frank'就是一個實參,實參是調用函數時傳遞給函數的信息。
傳遞實參
位置實參
你調用函數時,Python必須將函數調用中的每個實參都關聯到函數定義的一個形參。為此,最簡單的關聯方式是基於實參的順序,這種關聯方式被稱為位置實參,可以多次調用。
def introduce(name,age): '''自我介紹''' print("Hello! my name is " + name +" !" + "I'am " + age + " years old !") introduce('Frank','18') #運行結果 Hello! my name is Frank !I'am 18 years old !
關鍵字實參
可以直接將形參和實參關聯起來,這樣就不必要在意順序了。
def introduce(name,age): '''自我介紹''' print("Hello! my name is " + name +" !" + "I'am " + age + " years old !") introduce(age='18',name='Candy') #運行結果 Hello! my name is Candy !I'am 18 years old !
默認值
可以給函數的形參指定一個默認值,當你給形參重新指定值的時候,會覆蓋默認值。
def introduce(name,age='20'): '''自我介紹''' print("Hello! my name is " + name +" !" + "I'am " + age + " years old !") introduce(name='Candy') introduce(age='23',name='Frank') #運行結果 Hello! my name is Candy !I'am 20 years old ! Hello! my name is Frank !I'am 23 years old !
返回簡單值
函數並非總是直接顯示輸出,相反,它可以處理一些數據,並返回一個或一組值。函數返回的值被稱為返回值。
def get_formatted_name(first_name,last_name): '''返回整潔的姓名''' full_name = first_name + ' ' + last_name return full_name.title() musician = get_formatted_name('jimi','hendrix') print(musician) #運行結果 Jimi Hendrix
讓實參變為可選的
有的時候,我們不需要每個形參都有實參,但是沒有實參會導致輸出出錯,可以看一下下面的例子:
def get_formatted_name(first_name,last_name,middle_name=''): '''返回整潔的姓名''' if middle_name: full_name = first_name + ' ' + middle_name + ' ' + last_name else: full_name = first_name + ' ' + last_name return full_name.title() musician = get_formatted_name('jimi','hendrix') print(musician) musician = get_formatted_name('jimi','hendrix','dork') print(musician) #運行結果 Jimi Hendrix Jimi Dork Hendrix
看上面的例子,並非所有的人都中間名,所有我們在指定實參的時候,middle_name不一定要有,這里我們用''空字符串來指定middle_name的默認值(空字符串為False),再用if判斷用那種full_name的格式輸出。
返回字典
def build_person(first_name,last_name,age=''): '''返回一個值,其中包含一個人的信息''' person = {"first":first_name,"last":last_name} if age: person['age'] = age return(person) musician = build_person('jimi','hendrix','27') print(musician) #運行結果 {'first': 'jimi', 'last': 'hendrix', 'age': '27'}
函數可返回任何類型的值,包括列表和字典等較復雜的數據結構。
結合使用while循環和函數
def get_formatted_name(first_name,last_name): '''返回整潔的姓名''' full_name = first_name + " " + last_name return full_name.title() while True: f_name = input("Please input your first name:") l_name = input("Please input your last name:") name = get_formatted_name(f_name,l_name) print("hello! " + name) #運行結果 Please input your first name:bin Please input your last name:liu hello! Bin Liu Please input your first name:
函數括號里面也可以是被賦值的變量名。
傳遞列表
可以將一個列表傳遞給形參
def greet_users(names): '''遍歷列表,打招呼''' for name in names: print("Hello, " + name + '!') usernames = ["Frank","May","Caroline"] greet_users(usernames) #運行結果 Hello, Frank! Hello, May! Hello, Caroline!
在函數中修改列表
def print_models(upprint,completed): '''彈出已打印的給完成的列表,並打印''' while upprint: current = upprint.pop() print("print:",current) completed.append(current) def show_models(completed): '''顯示已打印的''' print("The following models have been print:") for c in completed: print(c) upprint = ["apple","book","shirt"] completed = [] print_models(upprint,completed) show_models(completed) #運行結果 print: shirt print: book print: apple The following models have been print: shirt book apple
在這個例子中,函數執行結束后,upprint列表就空了,為了解決這個問題,可向函數傳遞列表的副本而不是原件,這樣函數所做的任何修改都只影響副本,而不會影響原件。
def print_models(upprint[:],completed):
傳遞任意數量的實參
def make_pizza(*toppings): '''概述要制作的pizza''' print("\nMaking a pizza with the following toppings:") for topping in toppings: print("--",topping) make_pizza('pepperoni') make_pizza('mushrooms','grenn peppers','extra cheese') #運行結果 Making a pizza with the following toppings: -- pepperoni Making a pizza with the following toppings: -- mushrooms -- grenn peppers -- extra cheese
形參名*toppings的星號讓Python創建一個名為toppings的空元祖,並將收到的所有值都封裝想到這個元祖中。
結合使用位置實參和任意數量實參
如果要讓函數接受不同類型的實參,必須在函數定義中將接納任意數量實參的形參放在最后。Python會先匹配實參和關鍵字實參,再將余下的實參都收集到最后一個形參中。
def make_pizza(size,*toppings): '''概述要制作的pizza''' print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("--",topping) make_pizza(16,'pepperoni') make_pizza(12,'mushrooms','grenn peppers','extra cheese') #運行結果 Making a 16-inch pizza with the following toppings: -- pepperoni Making a 12-inch pizza with the following toppings: -- mushrooms -- grenn peppers -- extra cheese
使用任意數量的關鍵字實參
def build_profile(first_name,last_name,**info): '''創建一個字典,其中包含我們知道的有關用戶的一切''' profile={} profile["first_name"]=first_name profile["last_name"]=last_name for k,v in info.items(): profile[k]=v return profile user_profile = build_profile("bin","liu",location="princeton",field="physics") print(user_profile) #運行結果 {'first_name': 'bin', 'last_name': 'liu', 'location': 'princeton', 'field': 'physics'}
將函數存儲在模塊中
#pizza打印方式模塊 def make_pizza1(size,*toppings): '''概述要制作的pizza''' print("\n Making a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("----" + topping) def make_pizza2(size,*toppings): '''概述要制作的pizza''' print("\nsize:",size) print("toppings:") for topping in toppings: print("====",topping)
在同一目錄下創建:pizza.py
#pizza import make_pizza make_pizza.make_pizza1(16,'pepperoni','mushrooms') make_pizza.make_pizza2(16,'pepperoni','mushrooms')
運行結果:
Making a 16-inch pizza with the following toppings: ----pepperoni ----mushrooms size: 16 toppings: ==== pepperoni ==== mushrooms
導入特定的函數
#pizza打印方式模塊 文件make_pizza.py def make_pizza1(size,*toppings): '''概述要制作的pizza''' print("\n Making a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("----" + topping) def make_pizza2(size,*toppings): '''概述要制作的pizza''' print("\nsize:",size) print("toppings:") for topping in toppings: print("====",topping) #pizza 文件pizza.py from make_pizza import make_pizza1,make_pizza2 make_pizza1(16,'pepperoni','mushrooms') make_pizza2(16,'pepperoni','mushrooms') #運行結果 Making a 16-inch pizza with the following toppings: ----pepperoni ----mushrooms size: 16 toppings: ==== pepperoni ==== mushrooms
使用as給函數定義別名
#pizza from make_pizza import make_pizza1 as pz1,make_pizza2 as pz2 pz1(16,'pepperoni','mushrooms') pz2(16,'pepperoni','mushrooms') #運行結果 Making a 16-inch pizza with the following toppings: ----pepperoni ----mushrooms size: 16 toppings: ==== pepperoni ==== mushrooms
語法:from module_name import function_name as fn
使用as給模塊定義別名
#pizza import make_pizza as pz pz.make_pizza1(16,'pepperoni','mushrooms') pz.make_pizza2(16,'pepperoni','mushrooms') #運行結果 Making a 16-inch pizza with the following toppings: ----pepperoni ----mushrooms size: 16 toppings: ==== pepperoni ==== mushrooms
語法:import module_name as mn
導入模塊中所有的函數
#pizza from make_pizza import * make_pizza1(16,'pepperoni','mushrooms') make_pizza2(16,'pepperoni','mushrooms') #運行結果 Making a 16-inch pizza with the following toppings: ----pepperoni ----mushrooms size: 16 toppings: ==== pepperoni ==== mushrooms
*可以代表前面指定模塊里的所有函數。