# Python 函數
> 原文: [https://thepythonguru.com/python-functions/](https://thepythonguru.com/python-functions/)
* * *
于 2020 年 1 月 7 日更新
* * *
函數是可重用的代碼段,可幫助我們組織代碼的結構。 我們創建函數,以便我們可以在程序中多次運行一組語句,而無需重復自己。
## 創建函數
* * *
Python 使用`def`關鍵字啟動函數,以下是語法:
```py
def function_name(arg1, arg2, arg3, .... argN):
? ? ?#statement inside function
```
**注意**:
函數內的所有語句均應使用相等的空格縮進。 函數可以接受零個或多個括在括號中的參數(也稱為參數)。 您也可以使用`pass`關鍵字來省略函數的主體,如下所示:
```py
def myfunc():
? ? pass
```
讓我們來看一個例子。
```py
def sum(start, end):
? ?result = 0
? ?for i in range(start, end + 1):
? ? ? ?result += i
? ?print(result)
sum(10, 50)
```
**預期輸出**:
```py
1230
```
上面我們定義了一個名為`sum()`的函數,它具有兩個參數`start`和`end`。 該函數計算從`start`到`end`開始的所有數字的總和。
## 具有返回值的函數。
* * *
上面的函數只是將結果打印到控制臺,如果我們想將結果分配給變量以進行進一步處理怎么辦? 然后,我們需要使用`return`語句。 `return`語句將結果發送回調用方并退出該函數。
```py
def sum(start, end):
? ?result = 0
? ?for i in range(start, end + 1):
? ? ? ?result += i
? ?return result
s = sum(10, 50)
print(s)
```
**預期輸出**:
```py
1230
```
在這里,我們使用`return`語句返回數字總和并將其分配給變量`s`。
您也可以使用`return`陳述式而沒有返回值。
```py
def sum(start, end):
if(start > end):
print("start should be less than end")
return # here we are not returning any value so a special value None is returned
? ?result = 0
? ?for i in range(start, end + 1):
? ? ? ?result += i
? ?return result
s = sum(110, 50)
print(s)
```
**預期輸出**:
```py
start should be less than end
None
```
在 python 中,如果您未從函數顯式返回值,則始終會返回特殊值`None`。 讓我們舉個例子:
```py
def test(): ? # test function with only one statement
? ? i = 100
print(test())
```
**預期輸出**:
```py
None
```
如您所見,`test()`函數沒有顯式返回任何值,因此返回了`None`。
## 全局變量與局部變量
* * *
**全局變量**:未綁定到任何函數但可以在函數內部和外部訪問的變量稱為全局變量。
**局部變量**:在函數內部聲明的變量稱為局部變量。
讓我們看一些例子來說明這一點。
**示例 1** :
```py
global_var = 12 # a global variable
def func():
? ? local_var = 100 # this is local variable
? ? print(global_var) # you can access global variables in side function
func() ? # calling function func()
#print(local_var) ? ? # you can't access local_var outside the function, because as soon as function ends local_var is destroyed
```
**預期輸出**:
```py
12
```
**示例 2**:
```py
xy = 100
def cool():
? ? xy = 200 # xy inside the function is totally different from xy outside the function
? ? print(xy) # this will print local xy variable i.e 200
cool()
print(xy) # this will print global xy variable i.e 100
```
**預期輸出**:
```py
200
100
```
您可以使用`global`關鍵字后跟逗號分隔的變量名稱(`,`)在全局范圍內綁定局部變量。
```py
t = 1
def increment():
global t # now t inside the function is same as t outside the function
t = t + 1
print(t) # Displays 2
increment()
print(t) # Displays 2
```
**預期輸出**:
```py
2
2
```
請注意,在全局聲明變量時不能為變量賦值。
```py
t = 1
def increment():
#global t = 1 # this is error
global t
t = 100 # this is okay
t = t + 1
print(t) # Displays 101
increment()
print(t) # Displays 101
```
**預期輸出**:
```py
101
101
```
實際上,無需在函數外部聲明全局變量。 您可以在函數內部全局聲明它們。
```py
def foo():
global x # x is declared as global so it is available outside the function
x = 100
foo()
print(x)
```
**預期輸出**: 100
## 具有默認值的參數
* * *
要指定參數的默認值,您只需要使用賦值運算符分配一個值。
```py
def func(i, j = 100):
? ? print(i, j)
```
以上函數具有兩個參數`i`和`j`。 參數`j`的默認值為`100`,這意味著我們可以在調用函數時忽略`j`的值。
```py
func(2) # here no value is passed to j, so default value will be used
```
**預期輸出**:
```py
2 100
```
再次調用`func()`函數,但這一次為`j`參數提供一個值。
```py
func(2, 300) # here 300 is passed as a value of j, so default value will not be used
```
**預期輸出**:
```py
2 300
```
## 關鍵字參數
* * *
有兩種方法可以將參數傳遞給方法:位置參數和關鍵字參數。 在上一節中,我們已經看到了位置參數的工作方式。 在本節中,我們將學習關鍵字參數。
關鍵字參數允許您使用像`name=value`這樣的名稱值對來傳遞每個參數。 讓我們舉個例子:
```py
def named_args(name, greeting):
? ? print(greeting + " " + name )
```
```py
named_args(name='jim', greeting='Hello')
named_args(greeting='Hello', name='jim') # you can pass arguments this way too
```
**期望值**:
```py
Hello jim
Hello jim
```
## 混合位置和關鍵字參數
* * *
可以混合使用位置參數和關鍵字參數,但是對于此位置參數必須出現在任何關鍵字參數之前。 我們來看一個例子。
```py
def my_func(a, b, c):
? ? print(a, b, c)
```
您可以通過以下方式調用上述函數。
```py
# using positional arguments only
my_func(12, 13, 14)
# here first argument is passed as positional arguments while other two as keyword argument
my_func(12, b=13, c=14)
# same as above
my_func(12, c=13, b=14)
# this is wrong as positional argument must appear before any keyword argument
# my_func(12, b=13, 14)
```
**預期輸出**:
```py
12 13 14
12 13 14
12 14 13
```
## 從函數返回多個值
* * *
我們可以使用`return`語句從函數中返回多個值,方法是用逗號(`,`)分隔它們。 多個值作為元組返回。
```py
def bigger(a, b):
? ? if a > b:
? ? ? ? return a, b
? ? else:
? ? ? ? return b, a
s = bigger(12, 100)
print(s)
print(type(s))
```
**預期輸出**:
```py
(100, 12)
<class 'tuple'>
```
在下一篇文章中,我們將學習 [Python 循環](/python-loops/)
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象