Python編程基礎(chǔ)之函數(shù)和模塊
一、函數(shù)和模塊概述
(一)函數(shù)概述
函數(shù)可以看成是語(yǔ)句的集合,通過(guò)函數(shù)調(diào)用來(lái)執(zhí)行其包含的語(yǔ)句。函數(shù)可以返回一個(gè)計(jì)算結(jié)果,根據(jù)每次函數(shù)調(diào)用的參數(shù),可以返回不同的計(jì)算結(jié)果。Python利用函數(shù)提高代碼的重用率,減少了代碼冗余。
執(zhí)行dir(__builtin__)
可以查看Python所有內(nèi)置對(duì)象
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'cell_count', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'debugcell', 'debugfile', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'runcell', 'runfile', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
演示Python內(nèi)置函數(shù)
?
(二)模塊概述
模塊是程序代碼和數(shù)據(jù)的封裝。模塊中定義的變量、函數(shù)或類等可導(dǎo)入到其他文件中使用。Python正是通過(guò)模塊提供各種功能,例如,在前面用到的sys
、os
、math
、random
等都是模塊。
1、sys模塊
查看sys模塊包含的對(duì)象(屬性和方法)
使用sys模塊的path
?2、os模塊
導(dǎo)入os模塊
獲取當(dāng)前工作目錄
?3、math模塊
4、random模塊
二、函數(shù)
- 在編寫(xiě)程序時(shí),往往會(huì)遇到在多處使用的類似代碼。這時(shí),可將重復(fù)代碼提取出來(lái),定義為函數(shù)。從而簡(jiǎn)化編程工作量,也使代碼結(jié)構(gòu)簡(jiǎn)化。
- 函數(shù)有三要素:函數(shù)名(
function name
)、參數(shù)列表(parameter list
)、返回值(return value
) - 參數(shù)有兩種類型:位置參數(shù)(
positional parameter)、
鍵參數(shù)(key parameter
)
(一)定義函數(shù)
1、語(yǔ)法格式
def: define
def 函數(shù)名(參數(shù)表): 函數(shù)體(語(yǔ)句組) return 返回值
如果我們定義一個(gè)函數(shù),沒(méi)有寫(xiě)return語(yǔ)句,系統(tǒng)會(huì)自動(dòng)給它添加一個(gè)return None
2、函數(shù)類型
- 無(wú)參函數(shù)
- 單參函數(shù)
- 多參函數(shù)
3、案例演示
定義無(wú)參函數(shù)
定義單參函數(shù)(調(diào)用時(shí)可以用位置參數(shù),也可以用鍵參數(shù))
定義多參函數(shù)
說(shuō)明:定義函數(shù)時(shí)的參數(shù)叫做形式參數(shù)(formal paramter),簡(jiǎn)稱形參(虛參);調(diào)用函數(shù)時(shí)的參數(shù)叫做實(shí)際參數(shù)(actual parameter),簡(jiǎn)稱實(shí)參。調(diào)用函數(shù),就是將實(shí)參傳遞給形參,進(jìn)行處理之后,得到返回值。
定義有返回值的函數(shù)
(二)調(diào)用函數(shù)
1、簡(jiǎn)要說(shuō)明
- 函數(shù)通過(guò)函數(shù)名加上一組圓括號(hào)進(jìn)行調(diào)用,參數(shù)放在圓括號(hào)內(nèi),多個(gè)參數(shù)之間用逗號(hào)分隔。
- 在Python中,所有的語(yǔ)句都是實(shí)時(shí)執(zhí)行的,不像C/C++存在編譯過(guò)程。def也是一條可執(zhí)行語(yǔ)句,定義一個(gè)函數(shù)。所以函數(shù)的調(diào)用必須在函數(shù)定義之后。
- 在Python中,函數(shù)名也是一個(gè)變量,它引用return語(yǔ)句返回的值,沒(méi)有返回值時(shí),函數(shù)值為None。
2、案例演示
編寫(xiě)并調(diào)用階乘函數(shù) - factorial(n)
運(yùn)行程序,查看結(jié)果
(三)函數(shù)參數(shù)
在定義函數(shù)時(shí),參數(shù)表中的各個(gè)參數(shù)稱為形式參數(shù),簡(jiǎn)稱形參。調(diào)用函數(shù)時(shí),參數(shù)表中提供的參數(shù)稱為實(shí)際參數(shù),簡(jiǎn)稱實(shí)參。在Python中,變量保存的是對(duì)象的引用,類似C/C++中的指針。實(shí)參傳遞給形參就是將對(duì)象的引用賦值給形參。
1、參數(shù)的多態(tài)性
多態(tài)是面向?qū)ο蟮囊粋€(gè)特點(diǎn),指多一個(gè)行為針對(duì)不同對(duì)象可能會(huì)得到不同的結(jié)果。Python中的變量無(wú)類型屬性,變量可引用各種不同類型的對(duì)象。同一個(gè)函數(shù),傳遞的實(shí)際參數(shù)類型不同時(shí),可獲得不同的結(jié)果,體現(xiàn)了多態(tài)性。
2、參數(shù)賦值傳遞
通常,函數(shù)調(diào)用時(shí)按參數(shù)的先后順序,將實(shí)參傳遞給形參。例如:調(diào)用add(1, 2.5)時(shí),1傳遞給a,2.5傳遞給b。Python允許以形參賦值的方式,指定將實(shí)參傳遞給形參。
三、利用函數(shù)實(shí)現(xiàn)模塊化
1、創(chuàng)建多級(jí)菜單系統(tǒng)
編寫(xiě)程序 - 多級(jí)菜單系統(tǒng).py
# -*- coding: utf-8 -*- """ 功能:多級(jí)菜單系統(tǒng) 作者:華衛(wèi) 日期:2021年1月4日 """ def add_record(): print('添加記錄功能尚待開(kāi)發(fā)') def query_record(): print('查詢記錄功能尚待開(kāi)發(fā)') def modify_record(): print('修改記錄功能尚待開(kāi)發(fā)') def delete_record(): print('刪除記錄功能尚待開(kāi)發(fā)') def login(): while True: print('主菜單') print('=============') print('1. 增加記錄') print('2. 查詢記錄') print('3. 修改記錄') print('4. 刪除記錄') print('5. 返回上級(jí)菜單') print('==============') mc2 = int(input('輸入菜單號(hào):')) if mc2 == 1: add_record() elif mc2 == 2: query_record() elif mc2 == 3: modify_record() elif mc2 == 4: delete_record() else: break while True: print('============') print('1. 登錄') print('2. 退出') print('============') mc1 = int(input('輸入菜單號(hào):')) if mc1 == 1: login() elif mc1 == 2: print('謝謝使用!') break
2、啟動(dòng)程序,查看效果
總結(jié)
篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
教你用Python實(shí)現(xiàn)Excel表格處理
今天教各位小伙伴怎么用Python處理excel,文中有非常詳細(xì)的代碼示例及相關(guān)知識(shí)總結(jié),對(duì)正在學(xué)習(xí)python的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05python+selenium?實(shí)現(xiàn)掃碼免密登錄示例代碼
這篇文章主要介紹了python+selenium?實(shí)現(xiàn)掃碼免密登錄,首先掃碼登錄獲取cookies保存到本地未后面免密登錄做準(zhǔn)備,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07Python+matplotlib實(shí)現(xiàn)循環(huán)作圖的方法詳解
這篇文章主要為大家介紹了Python如何利用matplotlib實(shí)現(xiàn)循環(huán)作圖的,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)學(xué)習(xí)2022-06-06基于Python 函數(shù)和方法的區(qū)別說(shuō)明
這篇文章主要介紹了基于Python 函數(shù)和方法的區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03Python+pyaudio實(shí)現(xiàn)音頻控制示例詳解
PyAudio?是語(yǔ)音處理的?Python?庫(kù),提供了比較豐富的功能。本文將利用pyaudio控制指定設(shè)備,實(shí)現(xiàn)錄制音頻、采集音頻流、播放音頻,感興趣的可以了解一下2022-07-07python+opencv實(shí)現(xiàn)霍夫變換檢測(cè)直線
這篇文章主要為大家詳細(xì)介紹了python+opencv實(shí)現(xiàn)霍夫變換檢測(cè)直線,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12python使用collections模塊的容器數(shù)據(jù)類型高效處理數(shù)據(jù)
這篇文章主要為大家介紹了python使用collections模塊的容器數(shù)據(jù)類型高效處理數(shù)據(jù)的方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06如何使用Python實(shí)現(xiàn)自動(dòng)化水軍評(píng)論
這篇文章主要介紹了如何使用Python實(shí)現(xiàn)自動(dòng)化水軍評(píng)論 ,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下2019-06-06python運(yùn)行或調(diào)用另一個(gè)py文件或參數(shù)方式
這篇文章主要介紹了python運(yùn)行或調(diào)用另一個(gè)py文件或參數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08python實(shí)現(xiàn)測(cè)試工具(二)——簡(jiǎn)單的ui測(cè)試工具
這篇文章主要介紹了python如何實(shí)現(xiàn)簡(jiǎn)單的ui測(cè)試工具,幫助大家更好的利用python進(jìn)行測(cè)試工作,感興趣的朋友可以了解下2020-10-10