前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python函数基础

python函数基础

作者头像
dogfei
发布2020-07-31 11:56:54
2930
发布2020-07-31 11:56:54
举报
文章被收录于专栏:devops探索devops探索

函数讲解

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

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)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 函数讲解
    • 位置参数
      • 关键字参数
        • 默认参数
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档