(function)
(return)
(scope)
(function)
定義函式
def 函式名稱(參數): 程式碼
呼叫函式
函式名稱(參數)
定義函式:將一段程式碼打包起來,變成一個函式
呼叫函式:需要用到該段程式碼時,用函式叫出來
簡單來說…數學的函數
老捧油-scratch
舉例#1
\begin{align}f(x)=(x+4)(6x^2+8x-4)+5x\end{align}
用python函式做做看
x = int(input()) print((x + 4)*(x**2 + 8*x - 4) + 5*x)
def f(x): print((x + 4)*(x**2 + 8*x - 4) + 5*x) #1~2行 定義函式 f(int(input())) #5行 呼叫函式
例題#1
請撰寫一個Python函式 \(\texttt{reverse_string(s)}\),該函式輸入一個字串s作為參數,並返回該字串的反轉版本。
def reverse_string(s): for i in range(len(s) - 1, -1, -1): print(s[i], end="") reverse_string(input())
def reverse_string(s): print(s[::-1]) reverse_string(input())
(return)
def f(a, b, c): return a**2 + b**2 + c**2
\(\texttt{return}\)的意思就是把程式碼的\(\texttt{f(a,b,c)}\)換成\(a^2 + b^2 + c^2\)
注意事項:
無\(\texttt{return}\)時預設返回\(\texttt{None}\)。
\(\texttt{return}\)後的代碼不會執行。
舉例#1
請撰寫一個Python函式\(\texttt{find_max_min(numbers)}\),該函式接受一個數字列表\(\texttt{numbers}\)作為參數,返回最大值和最小值(Max, Min)。如果列表為空,則返回 (None, None)。(本題以EOF結束)
input
3 1 4 1 5 9 2 6
-10 -20 0 5 3
#這行是沒東西
output
(9, 1)
(5, -20)
(None, None)
def find_max_min(numbers): if not numbers: # 檢查列表是否為空 return (None, None) max_value = max(numbers) # 找到最大值 min_value = min(numbers) # 找到最小值 return (max_value, min_value) try: while 1: numbers = list(map(int, input().split())) print(find_max_min(numbers)) except EOFError: None
例題#2
請寫一個Python函式\(\texttt{calculate_average(args)}\)
,該函式接受多個數字作為參數,並返回這些數字的平均值(必為整數)。如果沒有提供任何數字,則返回 0。(本題以EOF結束)
def calculate_average(args): if not args: return 0 return sum(args) // len(args) try: while 1: numbers = list(map(int, input().split())) print(calculate_average(numbers)) except EOFError: None
(scope)
在函數或類別外定義的變數。
在整個程式中都可以存取和修改。
x = 10 # 全域變數 def my_function(): print(x) # 可以在函數內部存取全域變數 my_function() # 輸出 10
在函數或類別方法內部定義的變數。
只能在定義區域內存取和修改。
當函數或方法執行完後,區域變數會被銷毀。
使用\(\texttt{global}\)關鍵字可以改成全域變數。
def my_function(): y = 5 # 區域變數 print(y) my_function() # 輸出 5 # print(y) # 錯誤,y 在函數外部不可見
def my_function(): global y y = 5 # 區域變數 print(y) my_function() # 輸出 5 print(y) # 輸出 5
在外層函數中定義的變數。
可以在內層函數中存取和修改。
使用\(\texttt{nonlocal}\)關鍵字可以在內層函數中存取和修改封閉變數。
def outer_function(): x = 10 # 封閉變數 def inner_function(): y = 5 # 區域變數 print(x) # 可以存取封閉變數 inner_function() outer_function() # 輸出 10 def modify_enclosing(): x = 10 def inner(): nonlocal x x = 20 # 使用 nonlocal 關鍵字修改封閉變數 inner() print(x) # 輸出 20 modify_enclosing()
Python 內建的一些變數和函式,例如\(\texttt{print()}\), \(\texttt{len()}\), \(\texttt{range()}\) 等。
在整個程式中都可以存取和使用。
Python官方-內建函式
Python會按照以下的搜尋順序來尋找變數:
簡單觀念題
在以下程式碼中,輸出的值是多少?
x = 5 def my_function(): x = 10 print(x) my_function()
https://rate.cx/rate?9270A3
https://rate.cx/PieCharts?9270A3
例題#3