(1)寫函數(shù)時,可以為每個參數(shù)指定默認值。當調(diào)用函數(shù)為參數(shù)提供實際參數(shù)時,Python將使用指定的實際參數(shù);否則,將使用參數(shù)的默認值。因此,給參數(shù)指定默認值后,可以在函數(shù)調(diào)用中省略相應(yīng)的參數(shù)。
(2)使用默認值可以簡化函數(shù)調(diào)用,明確指出函數(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
實例擴展:
例如,如下程序為 name、message 形參指定了默認值:
# 為兩個參數(shù)指定默認值 def say_hi(name = "孫悟空", message = "歡迎來到腳本之家"): print(name, ", 您好") print("消息是:", message) # 全部使用默認參數(shù) say_hi() # 只有message參數(shù)使用默認值 say_hi("白骨精") # 兩個參數(shù)都不使用默認值 say_hi("白骨精", "歡迎學(xué)習(xí)Python") # 只有name參數(shù)使用默認值 say_hi(message = "歡迎學(xué)習(xí)Python")
運行結(jié)果為:
孫悟空 , 您好
消息是: 歡迎來到腳本之家
白骨精 , 您好
消息是: 歡迎來到腳本之家
白骨精 , 您好
消息是: 歡迎學(xué)習(xí)Python
孫悟空 , 您好
消息是: 歡迎學(xué)習(xí)Python
到此這篇關(guān)于python函數(shù)指定默認值的實例講解的文章就介紹到這了,更多相關(guān)python函數(shù)如何指定默認值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!