1、說(shuō)明
(1)寫函數(shù)時(shí),可以為每個(gè)參數(shù)指定默認(rèn)值。當(dāng)調(diào)用函數(shù)為參數(shù)提供實(shí)際參數(shù)時(shí),Python將使用指定的實(shí)際參數(shù);否則,將使用參數(shù)的默認(rèn)值。因此,給參數(shù)指定默認(rèn)值后,可以在函數(shù)調(diào)用中省略相應(yīng)的參數(shù)。
(2)使用默認(rèn)值可以簡(jiǎn)化函數(shù)調(diào)用,明確指出函數(shù)的典型用法。
2、實(shí)例
>>> def student(name, age=18):
... print('Hello, My name is ' + name + ', I am ' + str(age) + ' years old')
...
>>> student('bob')
Hello, My name is bob, I am 18 years old
>>> student('nicole')
Hello, My name is nicole, I am 18 years old
>>> student('bob', 20)
Hello, My name is bob, I am 20 years old
實(shí)例擴(kuò)展:
例如,如下程序?yàn)?name、message 形參指定了默認(rèn)值:
# 為兩個(gè)參數(shù)指定默認(rèn)值
def say_hi(name = "孫悟空", message = "歡迎來(lái)到腳本之家"):
print(name, ", 您好")
print("消息是:", message)
# 全部使用默認(rèn)參數(shù)
say_hi()
# 只有message參數(shù)使用默認(rèn)值
say_hi("白骨精")
# 兩個(gè)參數(shù)都不使用默認(rèn)值
say_hi("白骨精", "歡迎學(xué)習(xí)Python")
# 只有name參數(shù)使用默認(rèn)值
say_hi(message = "歡迎學(xué)習(xí)Python")
運(yùn)行結(jié)果為:
孫悟空 , 您好
消息是: 歡迎來(lái)到腳本之家
白骨精 , 您好
消息是: 歡迎來(lái)到腳本之家
白骨精 , 您好
消息是: 歡迎學(xué)習(xí)Python
孫悟空 , 您好
消息是: 歡迎學(xué)習(xí)Python
到此這篇關(guān)于python函數(shù)指定默認(rèn)值的實(shí)例講解的文章就介紹到這了,更多相關(guān)python函數(shù)如何指定默認(rèn)值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!