什么是python的必選參數(shù)
函數(shù)的必選參數(shù),指的是函數(shù)調(diào)用的時(shí)候必須傳入的參數(shù)
import mathdef cal (n): return n * nvar = cal(2)print(var) # 4
上面的函數(shù)是計(jì)算一個(gè)數(shù)的平方,當(dāng)要計(jì)算n^3, n^4.... 只能傳入2個(gè)必選參數(shù)
def cal_update(n,m): return int(math.pow(n,m))var = cal_update(2,4)print(var) # 16
但是,如果大多數(shù)情況下,都是平方計(jì)算,那每次都 cal_updtae(n,2)就會(huì)很麻煩,因此引入了默認(rèn)參數(shù)
默認(rèn)參數(shù),默認(rèn)情況下的傳入的參數(shù)
def cal_update2(n,m=2): return int(math.pow(n,m))var = cal_update2(3) # 只需傳入一個(gè)參數(shù),默認(rèn)傳入2print(var) # 9
內(nèi)容擴(kuò)展:
Python python 函數(shù)參數(shù):必選參數(shù),默認(rèn)參數(shù)代碼實(shí)例:
import math# 函數(shù)的必選參數(shù)’’’函數(shù)的必選參數(shù),指的是函數(shù)調(diào)用的時(shí)候必須傳入的參數(shù) ’’’def cal (n): return n * nvar = cal(2)print(var) # 4’’’上面的函數(shù)是計(jì)算一個(gè)數(shù)的平方,當(dāng)要計(jì)算n^3, n^4.... 只能傳入2個(gè)必選參數(shù) ’’’def cal_update(n,m): return int(math.pow(n,m))var = cal_update(2,4)print(var) # 16’’’但是,如果大多數(shù)情況下,都是平方計(jì)算,那每次都 cal_updtae(n,2)就會(huì)很麻煩,因此引入了默認(rèn)參數(shù) ’’’# 函數(shù)的默認(rèn)參數(shù)’’’默認(rèn)參數(shù),默認(rèn)情況下的傳入的參數(shù) ’’’def cal_update2(n,m=2): return int(math.pow(n,m))var = cal_update2(3) # 只需傳入一個(gè)參數(shù),默認(rèn)傳入2print(var) # 9def student(name,sex,city=’shanghai’,age=’20’): print (’name:’, name) print(’sex:’, sex) print(’city:’, city) print(’age:’, age)student(’chris’,’male’)# name: chris# sex: male# city: shanghai# age: 20’’’默認(rèn)參數(shù)必須是不變對(duì)象,若是可變的對(duì)象可能出現(xiàn)問(wèn)題 ’’’def count(name=[]): name.append(’chris’) print(name) return namecount(name=[’sarah’,’Tom’])# [’sarah’, ’Tom’, ’chris’]count();# [’chris’]count()# [’chris’, ’chris’] 當(dāng)我重新調(diào)用這個(gè)函數(shù)的時(shí)候,默認(rèn)參數(shù)name 并不是[],而是上一次沒(méi)有清空的[’chris’]’’’默認(rèn)參數(shù)是一個(gè)變量,函數(shù)定義的同時(shí),已經(jīng)被計(jì)算出來(lái),若是有變化,它會(huì)指向新的地址 ’’’
到此這篇關(guān)于什么是python的必選參數(shù)的文章就介紹到這了,更多相關(guān)python必選參數(shù)是什么意思內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. chat.asp聊天程序的編寫(xiě)方法2. JSP之表單提交get和post的區(qū)別詳解及實(shí)例3. 利用FastReport傳遞圖片參數(shù)在報(bào)表上展示簽名信息的實(shí)現(xiàn)方法4. PHP循環(huán)與分支知識(shí)點(diǎn)梳理5. Ajax請(qǐng)求超時(shí)與網(wǎng)絡(luò)異常處理圖文詳解6. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能7. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法8. ASP中格式化時(shí)間短日期補(bǔ)0變兩位長(zhǎng)日期的方法9. JavaWeb Servlet中url-pattern的使用10. jsp EL表達(dá)式詳解
