Python 基礎(chǔ)知識(shí)全篇-函數(shù)(Functions)

函數(shù)是什么

函數(shù)是一組操作的集合,并賦予它一個(gè)名字。你已經(jīng)使用過(guò)許多 Python 內(nèi)置的函數(shù),例如?string.title()?和?list.sort()?。我們也可以定義自己的函數(shù),它們可以“教導(dǎo)” Python 作一些新的行為。

通用語(yǔ)法

一個(gè)函數(shù)通常如下所示:

# Let's define a function.

def function_name(argument_1, argument_2):

? ? # Do whatever we want this function to do,

? ? #? using argument_1 and argument_2

# Use function_name to call the function.

function_name(value_1, value_2)

這段代碼并不能運(yùn)行,但顯示了函數(shù)的通常用法。

定義一個(gè)函數(shù)

使用關(guān)鍵字?def?告訴 Python 你將要定義一個(gè)函數(shù)。

給你的函數(shù)起一個(gè)名字。函數(shù)名應(yīng)當(dāng)能表明函數(shù)是干什么的。

給函數(shù)需要的數(shù)據(jù)起名稱。

它們是變量名,而且只在函數(shù)里用。

這些名稱被稱為函數(shù)的參數(shù)(arguments

確保函數(shù)的定義以冒號(hào)結(jié)束。

在函數(shù)內(nèi)部,寫下任意你想要的代碼。

使用你的函數(shù)

函數(shù)名后跟圓括號(hào)調(diào)用函數(shù)。

在圓括號(hào)中,給出函數(shù)運(yùn)行需要的數(shù)據(jù)。

函數(shù)中的參數(shù)可以是變量,例如?current_name?和?current_age,也可以是實(shí)際的數(shù)據(jù),例如 'eric' 和 5。

示例

第一個(gè)例子

第一個(gè)簡(jiǎn)單的例子,我們實(shí)現(xiàn)一個(gè)道賀的程序。我們先實(shí)現(xiàn)一個(gè)不用函數(shù)的版本,嘗試去理解函數(shù)的作用。如下所示:

print("You are doing good work, Adriana!")

print("Thank you very much for your efforts on this project.")

print("\nYou are doing good work, Billy!")

print("Thank you very much for your efforts on this project.")

print("\nYou are doing good work, Caroline!")

print("Thank you very much for your efforts on this project.")

上述代碼有很多重復(fù)的地方,函數(shù)就是用來(lái)替代重復(fù)的代碼,在需要的地方引用它。使用函數(shù)后的代碼如下所示:

def thank_you(name):

? ? # This function prints a two-line personalized thank you message.

? ? print("\nYou are doing good work, %s!" % name)

? ? print("Thank you very much for your efforts on this project.")


thank_you('Adriana')

thank_you('Billy')

thank_you('Caroline')

在初始代碼中,每條被打印的語(yǔ)句中,除了名字其他部分都是相同的。當(dāng)你看到這樣的重復(fù)語(yǔ)句后,就可以使用函數(shù)使你的程序更有效率。

一個(gè)常見(jiàn)的錯(cuò)誤

函數(shù)一定要在使用之前定義。否則就會(huì)引起錯(cuò)誤。示例如下:

thank_you('Adriana')

thank_you('Billy')

thank_you('Caroline')

def thank_you(name):

? ? # This function prints a two-line personalized thank you message.

? ? print("\nYou are doing good work, %s!" % name)

? ? print("Thank you very much for your efforts on this project.")

第一行先調(diào)用了函數(shù),但是 Python 不知道如何運(yùn)行這個(gè)函數(shù)。只有在調(diào)用它之前定義才能正確運(yùn)行。

第二個(gè)例子

在我們介紹列表中的排序方法時(shí),寫了很多重復(fù)的代碼。讓我們先來(lái)看看不使用函數(shù)情況下的代碼。如下所示:

students = ['bernice', 'aaron', 'cody']

# Put students in alphabetical order.

students.sort()

# Display the list in its current order.

print("Our students are currently in alphabetical order.")

for student in students:

? ? print(student.title())

# Put students in reverse alphabetical order.

students.sort(reverse=True)

# Display the list in its current order.

print("\nOur students are now in reverse alphabetical order.")

for student in students:

? ? print(student.title())

接下來(lái)使用函數(shù)來(lái)實(shí)現(xiàn)相同的功能。代碼如下所示:

def show_students(students, message):

? ? # Print out a message, and then the list of students

? ? print(message)

? ? for student in students:

? ? ? ? print(student.title())

students = ['bernice', 'aaron', 'cody']

# Put students in alphabetical order.

students.sort()

show_students(students, "Our students are currently in alphabetical order.")

#Put students in reverse alphabetical order.

students.sort(reverse=True)

show_students(students, "\nOur students are now in reverse alphabetical order.")

這段代碼就簡(jiǎn)潔的多了。我們想要顯示列表中的學(xué)生名字并展示一條提示信息。給這個(gè)操作賦予一個(gè)名字?show_students()?。

這個(gè)函數(shù)需要兩條信息來(lái)完成它的工作。學(xué)生列表和一條要展示的信息。在函數(shù)內(nèi)部,打印要展示的信息并循環(huán)打印學(xué)生列表。

現(xiàn)在為止我們的程序變得相當(dāng)簡(jiǎn)潔,我們只需要關(guān)注重復(fù)代碼中不同的部分即可。程序的可讀性也提高了。

使用函數(shù)的優(yōu)點(diǎn)

通過(guò)這些例子,你可能已經(jīng)體會(huì)到使用函數(shù)的好處:

在這個(gè)簡(jiǎn)單的例子中,我們節(jié)省了不少的工作量。在更大的程序中,將會(huì)節(jié)省更多的工作量。

當(dāng)一個(gè)函數(shù)可以工作后,我們不必?fù)?dān)心函數(shù)的代碼。每次在程序中重復(fù)使用函數(shù)時(shí),都是一次檢驗(yàn)函數(shù)的機(jī)會(huì)。每次發(fā)現(xiàn) bug 時(shí),只需要修改函數(shù)代碼而不必在每個(gè)重復(fù)的地方修改。

同理,在完善,增添代碼功能時(shí),只需要修改函數(shù)內(nèi)部代碼即可。

返回值

每個(gè)函數(shù)都可以返回一個(gè)值。返回值可以是當(dāng)前函數(shù)主要功能外無(wú)足輕重的功能,也可以是函數(shù)的主要功能。下述代碼通過(guò)數(shù)字返回相應(yīng)的單詞。

def get_number_word(number):

? ? # Takes in a numerical value, and returns

? ? #? the word corresponding to that number.

? ? if number == 1:

? ? ? ? return 'one'

? ? elif number == 2:

? ? ? ? return 'two'

? ? elif number == 3:

? ? ? ? return 'three'

? ? # ...


# Let's try out our function.

for current_number in range(0,4):

? ? number_word = get_number_word(current_number)

? ? print(current_number, number_word)

在上述代碼中,輸出的第一行是 None,這是一個(gè)邏輯錯(cuò)誤。函數(shù)接受一個(gè)參數(shù) 0,這個(gè)變量不在函數(shù) if 鏈的判斷范圍內(nèi),返回了一個(gè) None。我們需要添加一個(gè)else來(lái)處理不在判斷范圍內(nèi)的情況。如下所示:

def get_number_word(number):

? ? # Takes in a numerical value, and returns

? ? #? the word corresponding to that number.

? ? if number == 0:

? ? ? ? return 'zero'

? ? elif number == 1:

? ? ? ? return 'one'

? ? elif number == 2:

? ? ? ? return 'two'

? ? elif number == 3:

? ? ? ? return 'three'

? ? else:

? ? ? ? return "I'm sorry, I don't know that number."


# Let's try out our function.

for current_number in range(0,6):

? ? number_word = get_number_word(current_number)

? ? print(current_number, number_word)

如果你在函數(shù)中使用返回語(yǔ)句,謹(jǐn)記在碰到返回返回語(yǔ)句后函數(shù)會(huì)立即停止執(zhí)行。例如,我們可以在函數(shù)的返回語(yǔ)句后添加一條語(yǔ)句,這條語(yǔ)句永遠(yuǎn)都不會(huì)被執(zhí)行。如下所示:

def get_number_word(number):

? ? # Takes in a numerical value, and returns

? ? #? the word corresponding to that number.

? ? if number == 0:

? ? ? ? return 'zero'

? ? elif number == 1:

? ? ? ? return 'one'

? ? elif number == 2:

? ? ? ? return 'two'

? ? elif number == 3:

? ? ? ? return 'three'

? ? else:

? ? ? ? return "I'm sorry, I don't know that number."


? ? # This line will never execute, because the function has already

? ? #? returned a value and stopped executing.

? ? print("This message will never be printed.")


# Let's try out our function.

for current_number in range(0,6):

? ? number_word = get_number_word(current_number)

? ? print(current_number, number_word)

想一想

我們只是簡(jiǎn)單的介紹一下函數(shù)。它還有更多的用法,接下來(lái)多多使用函數(shù),體會(huì)函數(shù)的不同用法。想一想下面的問(wèn)題:

如何給函數(shù)的參數(shù)賦初始值。

如何讓函數(shù)接受不同數(shù)量的參數(shù)。

動(dòng)手試一試

Greeter

寫下一個(gè)函數(shù),參數(shù)是一個(gè)人的名字,并打印出一條祝福的語(yǔ)句。

用你的函數(shù)祝福3個(gè)人。

將人名存儲(chǔ)在列表中,并且用?for?循環(huán)調(diào)用函數(shù)。

Full Names

寫下一個(gè)函數(shù),參數(shù)包括姓和名字,并打印出一條包含全名的語(yǔ)句。

使用不同的參數(shù),調(diào)用 3 次你的函數(shù)。

Addition Calculator

寫下一個(gè)函數(shù),包含兩個(gè)數(shù)字類型的參數(shù)。計(jì)算參數(shù)的和并打印出參數(shù)和它們的和。

調(diào)用 3 次你的函數(shù)。

Return Calculator

修改 Addition Calculator 中的函數(shù),返回參數(shù)的和。并在函數(shù)外打印出來(lái)。

# Ex : Greeter

# put your code here

# Ex : Full Names

# put your code here

# Ex : Addition Calculator

# put your code here

# Ex : Return Calculator

# put your code here

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容