python函数基础

时间:2022-07-22
本文章向大家介绍python函数基础,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

函数讲解

函数如何定义这里不再讲解,从函数的参数讲起。先举一个例子来说明下:

1 2 3 4

def greet_user(username): print('Hello, ' + username.title() + '!') greet_user('devilf')

函数中的username为形参,用来让函数完成工作所需要的一些信息,greet_user('devilf')中的devilf为实参,实参是调用函数时传递给函数的信息。大体的过程是这样的:我们将devilf这个人名(实参)传递给了函数greet_user(),这个人名也就是这个实参存储在username中,然后进入函数体开始工作。

位置参数

就是基于实参的顺序进行关联,不能多不能少不能乱,多和少会报错,乱会改变其意义。

1 2 3 4 5 6 7

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('hamster','harry')

关键字参数

1 2 3 4 5 6 7

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('hamster','harry') describe_pet(pet_name='kitty',animal_type='cat')

关键字可以不用考虑顺序的问题。

默认参数

定义函数时如果指定了默认参数,若实参中没有指定该默认参数则按默认输出,否则按指定的给出。

1 2 3 4 5 6

def describe_pet(pet_name,animal_type='dog'): print('nI have a ' + animal_type.title() + '.') print('My ' + animal_type + "'s name is " + pet_name.title() + '.') describe_pet(pet_name='tom') describe_pet(pet_name='alice',animal_type='cat')

小练习:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

def describe_city(city_name,son_city): print(son_city.title() + ' is in ' + city_name.title() + '.') citys = { 'china': ['beijing','shanghai','shandong','tengzhou'], 'usa': ['miami','texas','oklahoma'], 'japan': ['tokyo','osaka'], } for city,son in citys.items(): num = len(son) if num != 1: for son_son in son: describe_city(city_name=city,son_city=son_son) else: describe_city(city_name=city,son_city=son_son)