Python基础教程:自定义函数
生活随笔
收集整理的這篇文章主要介紹了
Python基础教程:自定义函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
函數的形式:
def name(param1, param2, ..., paramN):statementsreturn/yield value # optional- 和其他需要編譯的語言(比如 C 語言)不一樣的是,def 是可執行語句,這意味著函數直到被調用前,都是不存在的。當程序調用函數時,def 語句才會創建一個新的函數對象,并賦予其名字。
- Python 是 dynamically typed ,對函數參數來說,可以接受任何數據類型,這種行為在編程語言中稱為多態。所以在函數里必要時要做類型檢查,否則可能會出現例如字符串與整形相加出異常的情況。
函數的嵌套:
例:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' def f1():print('hello')def f2():print('world')f2() f1() 'hello' 'world'嵌套函數的作用
保證內部函數的隱私
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' def connect_DB():def get_DB_configuration():...return host, username, passwordconn = connector.connect(get_DB_configuration())return conn在connect_DB函數外部,并不能直接訪問內部函數get_DB_configuration,提高了程序的安全性
如果在需要輸入檢查不是很快,還會耗費一定資源時,可以使用函數嵌套提高運行效率。
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' def factorial(input):# validation checkif not isinstance(input, int):raise Exception('input must be an integer.')if input < 0:raise Exception('input must be greater or equal to 0' )...def inner_factorial(input):if input <= 1:return 1return input * inner_factorial(input-1)return inner_factorial(input) print(factorial(5))函數作用域
1.global
在Python中,我們不能在函數內部隨意改變全局變量的值,會報local variable ‘VALUE’ referenced before assignment。
下例通過global聲明,告訴解釋器VALUE是全局變量,不是局部變量,也不是全新變量
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' VALUE = 10 LIST = ['a','b'] print(id(LIST)) #2490616668744 def validation_check(value):global VALUEVALUE += 3 #如果注釋掉global VALUE,會報local variable 'VALUE' referenced before assignmentLIST[0] = 10 #可變類型無需global可以使用全局變量?print(id(LIST)) #2490616668744print(f'in the function VALUE: {LIST}') #in the function VALUE: [10, 'b']print(f'in the function VALUE: {VALUE}') #in the function VALUE: 13validation_check(1) print(f'out of function {LIST}') #out of function [10, 'b'] print(f'out of function {VALUE}') #out of function 13 #a: 13 #b: 132.nonlocal
對于嵌套函數,nonlocal 聲明變量是外部函數中的變量
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' def outer():x = "local"def inner():nonlocal x # nonlocal 關鍵字表示這里的 x 就是外部函數 outer 定義的變量 xx = 'nonlocal'print("inner:", x)inner()print("outer:", x) outer() # inner :nonlocal # outer :nonlocal當內部變量與外部變量同名時,內部變量會覆蓋外部變量
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' def outer():x = "local"def inner():x = 'nonlocal' # 這里的 x 是 inner 這個函數的局部變量print("inner:", x)inner()print("outer:", x) outer() # 輸出 # inner: nonlocal # outer: local閉包
內部函數返回一個函數
外部函數nth_power()中的exponent參數在執行完nth_power()后仍然會被內部函數exponent_of記住
總結
以上是生活随笔為你收集整理的Python基础教程:自定义函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python基础教程:用模块化来搭项目
- 下一篇: 我不想用for循环