Python 初學者教程/函式
在我們之前的課程中,我說過我們會深入研究有目的的程式設計。這涉及使用者輸入,使用者輸入需要一個叫做函式的東西。
什麼是函式?實際上,函式是執行特定任務的小型獨立程式,你可以將它們合併到自己的大型程式中。建立函式後,你可以隨時隨地使用它。這樣可以節省你每次執行常見任務時不得不重複告訴計算機該做什麼的時間和精力,例如讓使用者輸入一些內容。
Python 有很多預製函式。你現在就可以使用這些預製函式,只需“呼叫”它們。“呼叫”函式是指你向函式提供輸入,它會返回一個值(就像變數一樣)作為輸出。不理解?以下是呼叫函式的一般形式
- 程式碼示例 1 - 如何呼叫函式
function_name(parameters)
看到了嗎?很簡單。
function_name 指示你想使用的函式(你應該知道......)。例如,函式 raw_input(此函式在 Python 3 中已重新命名為 input),將是我們使用的第一個函式。引數是你傳遞給函式的值,告訴它應該做什麼,以及如何做。例如,如果一個函式將任何給定的數字乘以 5,引數中的內容告訴函式應該將哪個數字乘以 5。將數字 70 放入引數中,函式將執行 70×5。
好吧,程式可以將一個數字乘以 5,但這有什麼意義呢?一種溫暖模糊的感覺?你的程式需要看到發生的事情的結果,看看 70 x 5 是多少,或者看看是否哪裡出了問題(比如你給了它一個字母而不是數字)。那麼函式如何顯示它做了什麼呢?
實際上,當計算機執行一個函式時,它實際上看不到函式名,而是看到函式執行的結果。變數做的事情完全一樣 - 計算機看不到變數名,而是看到變數中儲存的值。讓我們把這個將任何數字乘以 5 的程式稱為 multiply()。你將想要乘以的數字放在括號中。所以如果你輸入了這個
- 程式碼示例 2 - 使用函式
a = multiply(70)
計算機實際上會看到這個
- 程式碼示例 3 - 計算機看到的
a = 350
注意:不要嘗試輸入此程式碼 - multiply() 不是一個真實函式,除非你建立它。
函式執行自身,然後根據它接收的引數返回一個數字給主程式。
現在讓我們用一個真實的函式試試,看看它做了什麼。這個函式叫做 input,它會提示使用者輸入一些內容。然後它將輸入的內容轉換為文字字串。嘗試以下程式碼
- 程式碼示例 4 - 使用 input
# this line makes 'a' equal to whatever you type in, change "raw_input" to "input" for python 3.0
a = raw_input("Type in something, and it will be repeated on screen:")
# this line prints what 'a' is now worth
print(a)
假設在上面的程式中,你輸入了“hello”當它提示你輸入一些內容時。對於計算機來說,這個程式看起來像這樣
- 程式碼示例 5 - 計算機看到的
a = "hello"
print("hello")
記住,變數只是一個儲存的值。對於計算機來說,變數“a”不像“a”那樣看起來 - 它看起來像儲存在它裡面的值。函式類似 - 對於主程式(即執行函式的程式)來說,它們看起來像它們執行時返回的值。
讓我們寫另一個程式,它將充當計算器。這次它將執行比我們之前更冒險的事情。將會有一個選單詢問你是否要將兩個數字相乘、將兩個數字相加、將一個數字除以另一個數字,或者從一個數字中減去另一個數字。唯一的問題是raw_input函式將你輸入的內容作為字串返回,而我們想要數字 1,而不是字母 1(是的,在 Python 中,兩者是有區別的)。
幸運的是,有人寫了函式input(在 Python 3 中為 eval(input())),它將你輸入的內容作為數字返回給主程式 - 但關鍵的是,作為數字,而不是字母。如果你輸入一個整數(一個整數),從 input 中返回的值就是一個整數。如果你將這個整數放入一個變數中,該變數將成為一個整數型別的變數,這意味著你可以在它上面執行加法、減法和其他數學運算。
現在,讓我們適當地設計這個計算器。我們想要一個每次完成加法、減法等操作後都會返回的選單。換句話說,要迴圈(提示!!!)while(大提示!!!)你告訴程式應該繼續執行。
我們希望它執行與你輸入的數字相關的選單選項。這意味著你需要輸入一個數字(即輸入)和一個if迴圈。
讓我們先用通俗易懂的英語把它寫出來
- 程式碼示例 6 - 人類語言示例
START PROGRAM
print opening message
while we let the program run, do this:
#Print what options you have
print Option 1 - add
print Option 2 - subtract
print Option 3 - multiply
print Option 4 - divide
print Option 5 - quit program
ask the person what option they want and look for an integer
if it is option 1:
ask for first number
ask for second number
add them together
display the result on screen
if it is option 2:
ask for first number
ask for second number
subtract one from the other
display the result on screen
if it is option 3:
ask for first number
ask for second number
multiply them
display the result on screen
if it is option 4:
ask for first number
ask for second number
divide the first by the second
display the result on screen
if it is option 5:
tell the loop to stop
Display a goodbye message on screen
END PROGRAM
讓我們把它轉換成 Python 能夠理解的語言
- 程式碼示例 7 - 選單的 Python 版本
#calculator program
#This variable tells the loop whether it should loop or not.
# 1 means loop. Anything else means don't loop.
loop = 1
#this variable holds the user's choice in the menu:
choice = 0
while loop == 1:
#Display the available options
print ("Welcome to calculator.py")
print ("your options are:")
print (" ")
print ("1) Addition")
print ("2) Subtraction")
print ("3) Multiplication")
print ("4) Division")
print ("5) Quit calculator.py")
print (" ")
choice = int(input("Choose your option: "))
if choice == 1:
add1 = int(input("Add this: "))
add2 = int(input("to this: "))
print (add1, "+", add2, "=", add1 + add2)
elif choice == 2:
sub2 = int(input("Subtract this: "))
sub1 = int(input("from this: "))
print (sub1, "-", sub2, "=", sub1 - sub2)
elif choice == 3:
mul1 = int(input("Multiply this: "))
mul2 = int(input("with this: "))
print (mul1, "*", mul2, "=", mul1 * mul2)
elif choice == 4:
div1 = int(input("Divide this: "))
div2 = int(input("by this: "))
print (div1, "/", div2, "=", div1 / div2)
elif choice == 5:
loop = 0
print("Thank you for using calculator.py!")
哇!這是一個令人印象深刻的程式!把它貼上到 Python IDLE 中,儲存為“calculator.py”並執行它。試著玩玩 - 嘗試所有選項,輸入整數(沒有小數點的數字),以及小數點後面的數字(在程式設計中稱為浮點數)。嘗試輸入文字,看看程式如何出現輕微錯誤並停止執行(這可以透過錯誤處理來解決,我們將在後面討論)。
好吧,使用別人的函式固然很好,但是如果你想編寫自己的函式來節省時間,或者可能在其他程式中使用它們呢?這就是“def”運算子發揮作用的地方。(運算子只是告訴 python 該做什麼,例如“+”運算子告訴 python 進行加法,“if”運算子告訴 python 如果滿足條件就執行某些操作。)
這就是“def”運算子的工作方式
- 程式碼示例 8 - def 運算子
def function_name(parameter_1, parameter_2):
{this is the code in the function}
{more code}
{more code}
return {value to return to the main program}
{this code isn't in the function}
{because it isn't indented}
#remember to put a colon ":" at the end
#of the line that starts with 'def'
function_name 是函式的名稱。你將函式中的程式碼寫在該行下方,並縮排。(我們稍後再考慮 parameter_1 和 parameter_2,現在想象在括號之間什麼都沒有。
函式完全獨立於主程式執行。記住我說過當計算機遇到一個函式時,它看不到函式,而是看到一個值,即函式返回的值?以下是這句話
"對於計算機來說,變數“a”不像“a”那樣看起來 - 它看起來像儲存在它裡面的值。函式類似 - 對於主程式(即執行函式的程式)來說,它們看起來像它們執行時返回的值."
函式就像一個小型程式,一些引數被傳遞給它 - 然後它執行自身,然後返回一個值。你的主程式只看到返回的值。如果該函式飛往月球並返回,然後最後有
- 程式碼示例 9 - return
return "Hello"
那麼你的程式只會看到字串“hello”,在那裡函式的名稱。它不知道程式還做了什麼。
因為它是獨立的程式,函式看不到主程式中的任何變數,而主程式也看不到函式中的任何變數。例如,以下是一個函式,它在螢幕上列印單詞“hello”,然後將數字“1234”返回給主程式
- 程式碼示例 10 - 使用 return
# Below is the function
def hello():
print ("hello")
return 1234
# And here is the function being used
>>>hello()
想想上面程式碼的最後一行。它做了什麼?在程式中輸入(可以跳過註釋),看看它做了什麼。輸出看起來像這樣
- 程式碼示例 11 - 輸出
hello 1234
那麼發生了什麼?
當執行 'def hello()' 時,建立了一個名為 'hello' 的函式。當執行 'hello()' 時,函式 'hello' 被執行(執行其中的程式碼)。函式 'hello' 在螢幕上列印 "hello",然後將數字 '1234' 返回到主程式。現在主程式將該行視為 'print 1234',因此列印了 '1234'。這解釋了發生的一切。記住,主程式不知道螢幕上列印了 "hello"。它只看到了 '1234',並列印在螢幕上。
在這一堂(超大)課中,我們還有最後一件事要講 - 向函式傳遞引數。回憶一下我們如何定義函式
- 程式碼示例 12 - 用引數定義函式
def function_name(parameter_1,parameter_2):
{this is the code in the function}
{more code}
{more code}
return {value (e.g. text or number) to return to the main program}
在 (圓括號) 中,parameter_1 和 parameter_2 的位置,你輸入要將引數放入的變數名。輸入需要的任何數量,只要用逗號隔開。執行函式時,在圓括號中輸入的第一個值將放入 parameter_1 所在的變數中。第二個值(第一個逗號之後)將放入 parameter_2 所在的變數中。對於函式中存在的任何引數,這將繼續下去(從零到無限)。例如
- 程式碼示例 13 - 引數的工作原理
def funny_function(first_word, second_word, third_word):
print "The word created is: " + first_word + second_word + third_word
return first_word + second_word + third_word
執行上面的函式時,你可以輸入類似這樣的內容:funny_function("meat", "eater", "man")。第一個值(即 "meat")將放入名為 first_word 的變數中。方括號中的第二個值(即 "eater")將放入名為 second_word 的變數中,依此類推。這就是從主程式向函式傳遞值的方式 - 在圓括號內,在函式名稱之後。
回憶一下那個計算器程式。你認為它看起來有點亂嗎?我認為是的,所以讓我們用函式重寫它。
設計 - 首先,我們將用 'def' 運算子定義所有將要使用的函式(還記得運算子是什麼嗎?)。然後我們將使用主程式,用整潔的函式替換所有亂糟糟的程式碼。這樣,在未來再次檢視時,它會更容易理解。
- 程式碼示例 14 - 計算器程式
# calculator program
# NO CODE IS REALLY RUN HERE, IT IS ONLY TELLING US WHAT WE WILL DO LATER
# Here we will define our functions
# this prints the main menu, and prompts for a choice
def menu():
#print what options you have)
print ("Welcome to calculator.py")
print ("your options are:")
print (" ")
print ("1) Addition")
print ("2) Subtraction")
print ("3) Multiplication")
print ("4) Division")
print ("5) Quit calculator.py")
print (" ")
return int(input ("Choose your option: "))
# this adds two numbers given
def add(a,b):
print (a, "+", b, "=", a + b)
# this subtracts two numbers given
def sub(a,b):
print (b, "-", a, "=", b - a)
# this multiplies two numbers given
def mul(a,b):
print (a, "*", b, "=", a * b)
# this divides two numbers given
def div(a,b):
print (a, "/", b, "=", a / b)
# NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add(int(input("Add this: ")),int(input("to this: ")))
elif choice == 2:
sub(int(input("Subtract this: ")),int(input("from this: ")))
elif choice == 3:
mul(int(input("Multiply this: ")),int(input("by this: ")))
elif choice == 4:
div(int(input("Divide this: ")),int(input("by this: ")))
elif choice == 5:
loop = 0
print ("Thank you for using calculator.py!")
# NOW THE PROGRAM REALLY FINISHES
初始程式有 34 行程式碼。新程式實際上有 35 行程式碼!它稍微長一點,但如果你以正確的方式看待它,它實際上更簡單。
你將所有函式都定義在頂部。這實際上不屬於你的主程式 - 它們只是許多小程式,你將在以後呼叫它們。如果你需要它們,甚至可以在另一個程式中重用它們,而且不需要再告訴計算機如何加減。
如果你看一下程式的主要部分(在 'loop = 1' 和 'print "Thank you for..."' 行之間),它只有 15 行程式碼。這意味著如果你想用不同的方式編寫這個程式,你只需要編寫大約 15 行程式碼,而不是沒有函式時通常需要編寫的 34 行程式碼。
最後,作為一段插曲,我將解釋 add(input("Add this: "), input("to this: ")) 這行程式碼的含義。
我想將所有內容都放在一行上,並儘可能少用變數。還記得函式對主程式看起來像什麼嗎?它們返回的值。如果傳遞給 add() 函式的數字是 2 和 30,那麼主程式將看到以下內容
- 程式碼示例 15 - 複雜引數工作的結果
add(2, 30)
然後 add 程式將執行,將 2 和 30 相加,然後列印結果。add 程式沒有 'return' 運算子 - 它不會向主程式返回任何內容。它只是將兩個數字相加並列印在螢幕上,主程式看不到任何內容。
你可以用變數替換 (input("Add this: "), input("to this: ")) 作為 add 程式的引數。例如,
- 程式碼示例 16 - 變數作為引數
num1 = 45
num2 = 7
add(num1, num2)
對於上面的情況,請記住,你正在向其傳遞變數的函式無法更改變數本身 - 它們只是用作值。你甚至可以將值直接放入函式中
- 程式碼示例 17 - 最終結果
add(45, 7)
這是因為函式看到的只有作為引數傳遞的值。這些值將放入定義 'add' 時提到的變數中('def add(a,b)' 行)。然後,函式使用這些引數來完成其工作。
簡而言之
- 函式只能從主程式中看到傳遞給它的引數
- 主程式只能從函式中看到它傳遞回來的返回值