Python: 定义函数规则

 

向函数传递实参的方式很多,可使用位置实参 ,这要求实参的顺序与形参的顺序相同;也可使用关键

 

字实参 ,其中每个实参都由变量名和值组成;还可使用列表和字典。

位置实参:Python 将按顺序将函数调用中的实参关联到函数定义中相应的形参

def describe_pet(animal_type, pet_name):
""" 显示宠物的信息 """
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('harry', 'hamster')

关键字实参: 无需考虑函数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途

def describe_pet(animal_type, pet_name):
""" 显示宠物的信息 """
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(animal_type='hamster', pet_name='harry')

默认值:

编写函数时,可给每个形参指定默认值 。在调用函数中给形参提供了实参时, Python 将使用指定的实参值;否则,将使用形参的默认值。因此,给形参指定默认值后,可在函数调用中省略相应的实参。使用默认值可简化函数调用,还可清楚地指出函数的典型用法。

def describe_pet(pet_name, animal_type='dog'):
""" 显示宠物的信息 """
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')

你可能感兴趣的:(python)