卖逼视频免费看片|狼人就干网中文字慕|成人av影院导航|人妻少妇精品无码专区二区妖婧|亚洲丝袜视频玖玖|一区二区免费中文|日本高清无码一区|国产91无码小说|国产黄片子视频91sese日韩|免费高清无码成人网站入口

如何在Python中設(shè)置缺省參數(shù)

Python是一種功能強(qiáng)大的編程語(yǔ)言,可以通過(guò)設(shè)置缺省參數(shù)來(lái)提高代碼的效率和可讀性。 列表排序 當(dāng)我們需要對(duì)列表進(jìn)行排序時(shí),一般使用sort方法,默認(rèn)情況下會(huì)按照升序進(jìn)行排序: a [1, 8

Python是一種功能強(qiáng)大的編程語(yǔ)言,可以通過(guò)設(shè)置缺省參數(shù)來(lái)提高代碼的效率和可讀性。

列表排序

當(dāng)我們需要對(duì)列表進(jìn)行排序時(shí),一般使用sort方法,默認(rèn)情況下會(huì)按照升序進(jìn)行排序:

a  [1, 8, 2, 5]
()
print(a)

如果我們想要降序排列,可以通過(guò)傳入?yún)?shù)reverseTrue實(shí)現(xiàn):

a  [1, 8, 2, 5]
(reverseTrue)
print(a)

這里的reverseTrue就是一個(gè)缺省參數(shù)。

函數(shù)定義

我們經(jīng)常會(huì)遇到需要定義函數(shù)來(lái)判斷某個(gè)條件的情況,這時(shí)候使用缺省參數(shù)可以簡(jiǎn)化代碼。

def hello(person, t):
    print("%s is %s" % (person, t))
hello("杰克", "壞")

但是如果只有其中一方的情況比較多,輸入會(huì)變得很麻煩。這時(shí)可以使用缺省參數(shù):

def hello(person, tTrue):
    print("%s is %s" % (person, t))
hello("杰克")

通過(guò)設(shè)置缺省參數(shù),可以省去多次輸入同一個(gè)值的麻煩。

添加判斷條件

如果我們想要添加一個(gè)判斷條件,默認(rèn)為壞,可以這樣做:

def hello(person, tTrue):
    t  "壞"
    if not t:
        t  "好人"
    print("%s is %s" % (person, t))
hello("杰克")

這樣就不用多次輸入判斷條件了。

如果需要改變判斷條件,可以通過(guò)在函數(shù)調(diào)用時(shí)傳入?yún)?shù)實(shí)現(xiàn):

def hello(person, tTrue):
    tt  "壞"
    if not t:
        tt  "好人"
    print("%s is %s" % (person, tt))
hello("杰克", False)

在函數(shù)內(nèi)部需要添加一個(gè)額外的變量來(lái)判斷另一個(gè)條件。

缺省參數(shù)位置

在函數(shù)定義時(shí),缺省參數(shù)不能放在前面,必須放在后面。

def hello(tTrue, person):
    tt  "壞"
    if not t:
        tt  "好人"
    print("%s is %s" % (person, tt))
hello("杰克", False)

如果希望將缺省參數(shù)放在前面,只需在函數(shù)調(diào)用時(shí)更換位置即可:

def hello(person, tTrue, num88):
    tt  "壞"
    if not t:
        tt  "好人"
    print("%d%s is %s" % (num, person, tt))
hello("杰克", False)

當(dāng)然,我們也可以設(shè)置其他類型的缺省參數(shù)。

標(biāo)簽: