Hi 大家好,
今天要開始介紹基礎語法中的函數基礎篇,那我們開始吧!
舉個例子,日常生活中我們常使用的飲料販賣機,函數就像是一台飲料販賣機輸入: 在你投幣之後,選擇你想要喝的飲料輸出: 你會從飲料販賣機拿到一瓶飲料
函數就是會有「輸入」和「輸出」這樣的對應關係,函數名稱就是在這層關係上加上一個名稱
會使用函數的好處,就是我們可以不用知道函數內裝載的內容是什麼,只要呼叫函數名稱去執行函數,或是帶入函數需要的引數,就會得到你要的結果。同樣的函數內容可以重複利用,不需要再多做其它事情。
Python中定義函數使用def關鍵字,在def後面加上函數名稱,接著會加上(),最後要記得冒號:
定義一個 hi_python 的函數
def hi_python():
print("Hi, Python!")
記得第二行開始的內容要縮排,否則會發生錯誤
def hi_python():
print("Hi, Python!")
PS D:\Project\practice> python hello.py
File "D:\Project\practice\hello.py", line 2
print("Hi, Python!")
^
IndentationError: expected an indented block after function definition on line 1
PS D:\Project\practice>
如果函數內容還不知道要寫什麼,可以使用pass關鍵字來卡位,也是要記得縮排
def hi_python():
pass
可以使用函數名稱加上()來呼叫函數,同時執行函數內容
def hi_python(): <==== 定義函數
print("Hi, Python!")
hi_python() <==== 呼叫函數
PS D:\Project\practice> python hello.py
Hi, Python!
PS D:\Project\practice>
呼叫函數必須要在定義完函數之後呼叫,否則會發生錯誤,因為Python在解析的時候是逐行解析,所以無法在未定義之前就呼叫函數
hi_python() <==== 呼叫函數,會失敗,因為尚未定義
def hi_python(): <==== 定義函數
print("Hi, Python!")
PS D:\Project\practice> python hello.py
Traceback (most recent call last):
File "D:\Project\practice\hello.py", line 1, in <module>
hi_python()
^^^^^^^^^
NameError: name 'hi_python' is not defined
PS D:\Project\practice>
什麼是參數? 定義函數時候()內帶入的數
什麼是引數? 呼叫函數時候()內帶入的數
函數執行的結果可以根據你帶入不同的輸入而有所不同的輸出,函數內的內容可以不是寫死的
def hi_python(content): <==== content 就是參數
print(content)
hi_python("Hi, Python!") <==== "Hi, Python!" 就是引數
PS D:\Project\practice> python hello.py
Hi, Python!
PS D:\Project\practice>
帶入不同的引數
def hi_python(content):
print(content)
hi_python("Hello World!")
PS D:\Project\practice> python hello.py
Hello World!
PS D:\Project\practice>
函數有兩個參數,依傳入引數的位置順序來決定結果2和9是第一個引數,對應函數中的x參數,1和5是第二個引數,對應函數中的y參數
def minus(x, y):
return x - y
print(minus(2, 1))
print(minus(9, 5))
PS D:\Project\practice> python hello.py
1
4
PS D:\Project\practice>
函數有兩個參數,依傳入引數的關鍵字(參數名稱)來決定結果
傳入的引數前有加上參數名稱,所以函數會依引數名稱來取用值,傳入順序不影響結果
def minus(x, y):
return x - y
print(minus(x=2, y=1))
print(minus(y=5, x=9))
PS D:\Project\practice> python hello.py
1
4
PS D:\Project\practice>
位置引數要在關鍵字引數的前面
/ "前面"的所有參數a, b,一定只能使用位置引數方式帶入* "後面"的所有參數d, e, f,一定只能使用關鍵字引數方式帶入/ 和 * 中間沒有規範到的c,可以使用兩種引數方式帶入def hi(a, b, /, c, *, d, e, f):
print(a, b, c, d, e, f)
hi(1, 2, 3, e=5, f=6, d=4)
hi(1, 2, c=3, e=5, f=6, d=4)
PS D:\Project\practice> python hello.py
1 2 3 4 5 6
1 2 3 4 5 6
PS D:\Project\practice>
Q: 什麼是回傳值?
A: 就是函數最後輸出回傳出來的結果,在Python中會使用到return這個關鍵字
如果return後沒有回傳值,最後會得到None的結果
def add(a, b):
c = a + b
return
print(add(1, 1))
PS D:\Project\practice> python hello.py
None
PS D:\Project\practice>
如果return後有放回傳值,最後才會回傳正確的結果
def add(a, b):
c = a + b
return c <==== 這裡就是要回傳`變數c`的計算結果
print(add(1, 1))
PS D:\Project\practice> python hello.py
2
PS D:\Project\practice>
那今天就介紹到這裡,我們明天見~