如何在Python中設置缺省參數(shù)
Python是一種功能強大的編程語言,可以通過設置缺省參數(shù)來提高代碼的效率和可讀性。 列表排序 當我們需要對列表進行排序時,一般使用sort方法,默認情況下會按照升序進行排序: a [1, 8
Python是一種功能強大的編程語言,可以通過設置缺省參數(shù)來提高代碼的效率和可讀性。
列表排序
當我們需要對列表進行排序時,一般使用sort方法,默認情況下會按照升序進行排序:
a [1, 8, 2, 5]
()
print(a)
如果我們想要降序排列,可以通過傳入?yún)?shù)reverseTrue實現(xiàn):
a [1, 8, 2, 5]
(reverseTrue)
print(a)
這里的reverseTrue就是一個缺省參數(shù)。
函數(shù)定義
我們經(jīng)常會遇到需要定義函數(shù)來判斷某個條件的情況,這時候使用缺省參數(shù)可以簡化代碼。
def hello(person, t):
print("%s is %s" % (person, t))
hello("杰克", "壞")
但是如果只有其中一方的情況比較多,輸入會變得很麻煩。這時可以使用缺省參數(shù):
def hello(person, tTrue):
print("%s is %s" % (person, t))
hello("杰克")
通過設置缺省參數(shù),可以省去多次輸入同一個值的麻煩。
添加判斷條件
如果我們想要添加一個判斷條件,默認為壞,可以這樣做:
def hello(person, tTrue):
t "壞"
if not t:
t "好人"
print("%s is %s" % (person, t))
hello("杰克")
這樣就不用多次輸入判斷條件了。
如果需要改變判斷條件,可以通過在函數(shù)調用時傳入?yún)?shù)實現(xiàn):
def hello(person, tTrue):
tt "壞"
if not t:
tt "好人"
print("%s is %s" % (person, tt))
hello("杰克", False)
在函數(shù)內部需要添加一個額外的變量來判斷另一個條件。
缺省參數(shù)位置
在函數(shù)定義時,缺省參數(shù)不能放在前面,必須放在后面。
def hello(tTrue, person):
tt "壞"
if not t:
tt "好人"
print("%s is %s" % (person, tt))
hello("杰克", False)
如果希望將缺省參數(shù)放在前面,只需在函數(shù)調用時更換位置即可:
def hello(person, tTrue, num88):
tt "壞"
if not t:
tt "好人"
print("%d%s is %s" % (num, person, tt))
hello("杰克", False)
當然,我們也可以設置其他類型的缺省參數(shù)。