介紹
函數是一個包含指令的可呼叫單元,旨在減少程式碼重複並組織複雜的任務。有兩種類型:void 函數(無返回值)和有返回值的函數。
這是Python中函數的基本結構。
def function_name(args): function body
這是 Python 中 void 函數(無回傳值)的範例。
# create a function def hello(): print("hello!") # call the function hello()
輸出
hello!
基於上面的程式碼,建立了名為 hello() 的函數。透過指定函數名稱後面跟著括號 () 來呼叫函數。
這是一個有回傳值的函數範例。
# create a function with return value def add(a,b): return a + b result = add(2,4) print(result)
輸出
6
基於上面的程式碼,創建了名為 add() 的函數來對兩個數字求和。 add() 函數的回傳值儲存在 result 變數中。
使用傳回值函數時,請確保使用傳回值。
參數和關鍵字參數
Python 中的函數可以動態地接受多個參數。有兩種方法可以在函數中實現多個參數:
參數:多個參數在函數中實現,無需指定關鍵字。參數可以使用 *args.
來實現
關鍵字參數:多個參數在具有指定關鍵字的函數中實作。關鍵字參數可以使用 **kwargs 來實作。
參數和關鍵字參數都必須位於函數中參數定義的最後位置。
這是使用參數方法動態計算數字總和的多個參數實現的範例。
def sum(*args): result = 0 for arg in args: result += arg return result print(sum(1,2)) print(sum(1,2,3)) print(sum(1,2,3,4,5,4,3,2))
輸出
3 6 24
基於上面的程式碼,可以使用不同數量的參數來呼叫 sum() 函數。
這是使用關鍵字參數方法實作多個參數的範例。
def display_info(name,**kwargs): print("========") print(f"name: {name}") print("other informations") for k, val in kwargs.items(): print(f"{k}: {val}") print("========") display_info("john",job="programmer",company="acme inc") display_info("doe",job="programmer",company="acme inc",skills="go,java,php")
輸出
======== name: john other informations job: programmer company: acme inc ======== ======== name: doe other informations job: programmer company: acme inc skills: go,java,php ========
基於上面的程式碼,可以使用不同數量的參數來呼叫display_info()函數。透過使用**kwargs,可以用關鍵字定義參數。
參數和關鍵字參數可以一起使用。這是一個例子。
def display(*args,**kwargs): print("===========") print("items") for arg in args: print(arg) print("other information") for k, val in kwargs.items(): print(f"{k}: {val}") print("===========") display("apple","coffee","milk",payment="cash") display("TV","Camera",payment="cash",delivery="express")
輸出
=========== items apple coffee milk other information payment: cash =========== =========== items TV Camera other information payment: cash delivery: express ===========
遞迴函數
遞歸函數是在完成任務時呼叫自身的函數。遞歸函數可以解決很多問題,包括階乘數、斐波那契數列等等。
遞歸函數有兩個主要組成:
- 基本情況:基本情況定義函數何時停止。
- 遞迴關係:遞迴關係定義了函數的遞迴過程。
在此範例中,階乘計算是使用遞歸函數實現的。
def function_name(args): function body
輸出
# create a function def hello(): print("hello!") # call the function hello()
讓我們仔細看看階乘()函數。此函數涉及兩個組件:
基本情況:如果 n 的值等於 0 或 1,則函數執行終止。
遞迴關係:當n大於1時函數執行。
hello!
factorial() 函數如下圖所示。
拉姆達
lambda 是匿名函數。 lambda 可以包含許多參數,就像一般的函數一樣。 lambda 函數適合建立直接回傳值的小函數。
這是 sum() 函數的範例。
# create a function with return value def add(a,b): return a + b result = add(2,4) print(result)
這是 lambda 函數對兩個數字求和的範例。 lambda 函數儲存在名為 sum_func 的變數中。
6
要使用 lambda 函數,請透過變數名稱呼叫函數。
def sum(*args): result = 0 for arg in args: result += arg return result print(sum(1,2)) print(sum(1,2,3)) print(sum(1,2,3,4,5,4,3,2))
地圖和濾鏡
地圖功能
map() 函數為清單中的每個項目執行提供的回呼函數。
這是 map() 函數將每個數字乘以 3 的範例。
3 6 24
輸出
def display_info(name,**kwargs): print("========") print(f"name: {name}") print("other informations") for k, val in kwargs.items(): print(f"{k}: {val}") print("========") display_info("john",job="programmer",company="acme inc") display_info("doe",job="programmer",company="acme inc",skills="go,java,php")
基於上面的程式碼,triple()函數充當map()函數的回調,這意味著為數字列表中的每個項目呼叫triple()函數。然後,map() 函數的結果被轉換為列表,然後儲存在名為 result 的變數中。
上面的範例可以使用 lambda 函數來簡化。
======== name: john other informations job: programmer company: acme inc ======== ======== name: doe other informations job: programmer company: acme inc skills: go,java,php ========
輸出
def display(*args,**kwargs): print("===========") print("items") for arg in args: print(arg) print("other information") for k, val in kwargs.items(): print(f"{k}: {val}") print("===========") display("apple","coffee","milk",payment="cash") display("TV","Camera",payment="cash",delivery="express")
過濾功能
filter() 函數根據給定的回呼函數選擇清單中的項目。 filter() 函數適合使用提供的回呼函數過濾清單中的項目。 filter() 函數需要一個傳回布林值的回呼函數。
這是 filter() 函數只選取清單中偶數的範例。
=========== items apple coffee milk other information payment: cash =========== =========== items TV Camera other information payment: cash delivery: express ===========
輸出
def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n-1) # call the function result = factorial(5) print(result)
基於上面的程式碼,filter()函數使用is_even()作為回呼函數從列表中選擇偶數。
可以使用 lambda 函數簡化此範例。
120
輸出
def function_name(args): function body
範例 - 刪除重複程式碼
此功能可用於刪除重複程式碼。例如,有兩個函數,稱為register()和login()。這兩個函數都使用驗證過程。
# create a function def hello(): print("hello!") # call the function hello()
驗證過程有重複的程式碼。若要刪除這些重複項,可以將驗證過程包裝在單獨的函數中。
hello!
validate()函數可以在register()和login()函數內部使用。
# create a function with return value def add(a,b): return a + b result = add(2,4) print(result)
基於上面的程式碼,程式碼更乾淨,更容易修改,因為如果更新額外的驗證規則,可以在一個地方(validate()函數內部)更新驗證規則。
尖端
這些是在 Python 中使用函數時的關鍵技巧。
函數必須完成單一任務。如果需要多個任務,請為其他任務建立一個單獨的函數。
函數參數的最大數量為 3。如果參數看起來超過 3,請考慮為函數參數使用專用資料物件。
函數參數的最大數量似乎有爭議。
這是使用參數的 create_account() 函數的範例。
6
可以修改 create_account() 函數以使用資料物件來獲得更簡潔的程式碼。
def sum(*args): result = 0 for arg in args: result += arg return result print(sum(1,2)) print(sum(1,2,3)) print(sum(1,2,3,4,5,4,3,2))
- 使用文件來解釋功能描述。可以使用“””語法新增文件。
這是在函數內使用文件的範例。
3 6 24
來源
- 函數中的參數與關鍵字參數
- 遞歸函數圖解
希望這篇文章對你學習Python有幫助。如果您有任何意見,請在評論區告訴我。
以上是Python 教程 - 函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的關鍵特性包括:1.語法簡潔易懂,適合初學者;2.動態類型系統,提高開發速度;3.豐富的標準庫,支持多種任務;4.強大的社區和生態系統,提供廣泛支持;5.解釋性,適合腳本和快速原型開發;6.多範式支持,適用於各種編程風格。

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。