1.定义函数:使用关键字def来定义一个函数,向python指出函数名,还可能在括号内指出函数为完成其任务需要什么样的的信息。
2.实参和形参
a.形参:函数完成其工作所需要的一项信息
b.实参:调用函数时传递给函数的信息
# 此函数中username即为形参,'grace'是一个实参 def greet_user(username): print('hello, %s' % username) greet_user('grace')
3.传递实参
a.位置实参:实参的顺序与形参的顺序相同。使用位置实参调用函数时,实参的顺序很重要
def pet(pet_type, pet_name): print('this is a %s, his name is %s' % (pet_type, pet_name)) pet('dog', 'tom')
b.关键字实参是传递给函数的名称-值对,在调用函数时向python明确指出各个实参对应的形参,值关键字实参无需考虑函数调用中的实参顺序
def pet(pet_type, pet_name): print('this is a %s, his name is %s' % (pet_type, pet_name)) pet(pet_type='dog', pet_name='tom')
c.默认值:编写函数时,可以给每个形参指定默认值。在调用函数中给函数提供了实参时,python将使用指定的实参值,否则将使用形参的默认值。
使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的形参,这样的话python依然能够正确地解读位置实参
def name(first_name=input('input your first name: '), last_name=input('input your last name: ')): full_name = first_name + last_name return full_name.title() print(name())