七、函数2(2022-04-12)

6.返回字典

函数可一返回任何类型的值,包括列表和字典等较复杂的数据结构。

def build_guest_dict(last_name,first_name,age):
    guset = {'last_name':last_name,'first_name':first_name,'age':age}
    return guset
poet = build_guest_dict('bai','li',33)
print(poet)

{'last_name': 'bai', 'first_name': 'li', 'age': 33}

对以上函数进行扩展,加入更多形参

def build_guest_dict2(last_name,first_name,age=None,job=None):
    guest = {'last_name':last_name.title(),'first_name':first_name.title()}
    if age:
        guest['age'] = age
    if job:
        guest['job'] = job.title()
    return guest
poet = build_guest_dict2('du','fu',39)
print(poet)

{'last_name': 'Du', 'first_name': 'Fu', 'age': 39}
{'last_name': 'Wang', 'first_name': 'Wei', 'job': 'Singer'}

7.结合使用函数和while循环

def get_formatted_name3(last_name,first_name):
    full_name = f"{last_name} {first_name}"
    return full_name.title()
while True:
    print('Tell me your last_name')
    print("(Enter 'q' at any time to quit.)")
    l_name = input('last_name')
    if l_name == 'q':
        break
    f_name = input('first_name')
    if f_name == 'q':
        break
    full_names = get_formatted_name3(l_name,f_name)
    print(f"Hellow {full_names}")

Tell me your last_name
(Enter 'q' at any time to quit.)
last_name>? wang
first_name>? zejing
Hellow Wang Zejing

Tell me your last_name
(Enter 'q' at any time to quit.)
last_name>? wang
first_name>? wei
Hellow Wang Wei

Tell me your last_name
(Enter 'q' at any time to quit.)
last_name>? su
first_name>? shi
Hellow Su Shi

Tell me your last_name
(Enter 'q' at any time to quit.)
last_name>? q

8.传递列表

向函数传递列表很有用。将列表传递给函数后,函数就能直接访问其内容。

def greet_user(names):
    for name in names:
        message = f"hello,{name.title()}"
        print(message)
usernames = ['li bai','zhang jiu ling','su dong po']
greet_user(usernames)   

hello,Li Bai
hello,Zhang Jiu Ling
hello,Su Dong Po

9.在函数中修改列表

将列表传递给函数后,函数就可以对其进行修改,从而实现大批量处理数据。


unverified_users = ['Jack','Lance','Jhon','Sarapy']
verified_users = []
while unverified_users: #该循环持续弹出unverified_users列表中的元素,并追加至verified_users列表中。前列表为空时终止循环。
    verifying_user = unverified_users.pop()
    print(f"Now check the user: {verifying_user}")
    verified_users.append(verifying_user)
print(f"The following users have verified:")
for verified_user in verified_users:  #该循环遍历verified_users并打印
    print(verified_user)

Now check the user: Sarapy
Now check the user: Jhon
Now check the user: Lance
Now check the user: Jack
The following users have verified:
Sarapy
Jhon
Lance
Jack

以下通过定义两个函数,完成相同的工作。

def verify_users(unverified_users,verified_users):
    while unverified_users:
        verifying_user = unverified_users.pop()
        print(f"Now check the user: {verifying_user}")
        verified_users.append(verifying_user)
def show_verified_user(verified_users):
    print(f"THe follow users have verified:")
    for verified_user in verified_users:
        print(verified_user)

unverified_users2 = ['zhang heng','zu chong zhi','yang hui ','si ma guang']
verified_users2 = []

verify_users(unverified_users2,verified_users2)
show_verified_user(verified_users2)

Now check the user: si ma guang
Now check the user: yang hui
Now check the user: zu chong zhi
Now check the user: zhang heng
THe follow users have verified:
si ma guang
yang hui
zu chong zhi
zhang heng

每个函数都应该只负责一项具体的工作,同使函数中也可以调用函数。

10.禁止函数修改列表

有时候,需要函数调用列表元素,但又不能改变原列表,这就需要保留原列表。

这时候需要将列表的副本传递给函数,见如下代码:

def verify_users(unverified_users,verified_users):
    while unverified_users:
        verifying_user = unverified_users.pop()
        print(f"Now check the user: {verifying_user}")
        verified_users.append(verifying_user)
def show_verified_user(verified_users):
    print(f"THe follow users have verified:")
    for verified_user in verified_users:
        print(verified_user)

unverified_users2 = ['zhang heng','zu chong zhi','yang hui ','si ma guang']
verified_users2 = []

verify_users(unverified_users2[:],verified_users2) #unverified_users2[:] 表示将该列表的副本传递给函数
show_verified_user(verified_users2)
print(unverified_users2)  #打印原列表,发现列表并未变化

Now check the user: si ma guang
Now check the user: yang hui
Now check the user: zu chong zhi
Now check the user: zhang heng
THe follow users have verified:
si ma guang
yang hui
zu chong zhi
zhang heng
['zhang heng', 'zu chong zhi', 'yang hui ', 'si ma guang']

11.传递任意数量的参数

python允许函数从调用语句中收集任意数量的实参

def make_noodles(*toppings):
    print(toppings)
make_noodles('pepppers','beef','eggs','beans')
make_noodles('flour')

('pepppers', 'beef', 'eggs', 'beans')
('flour',)

12.结合使用位置实参和任意数量实参

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。

def make_noodles1(size,*toppings):
    print(f"Make {size}-noodles with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")

make_noodles1('thin','pappers','eggs','tomatos')    

Make thin-noodles with the following toppings:
-pappers
-eggs
-tomatos

13.使用任意数量的关键字实参

有时候需要接受任意数量的实参,但提前不知道传递给函数的具体信息。这种情况下可以将函数编写成能接受任意数量的键值对。

以下示例中,函数接受姓和名,还接受任意数量的关键字实参。


def build_profile(last,first,**user_info):
    user_info['last_name'] = last
    user_info['first_name'] = first    #创建了user_info字典,用于存放字典。
    return user_info
user_porfile = build_profile('xiao','hu',
                             age = 14,
                             weight = '135kg',
                             height = '177cm')
print(user_porfile)

{'age': 14, 'weight': '135kg', 'height': '177cm', 'last_name': 'xiao', 'first_name': 'hu'}

14.前面知识的巩固与练习

(1))三明治菜单.注意形参为单星号,如函数又返回值,其返回值为元组。

*args格式的形参,用于收集任意数量的位置实参。

def make_sandwich(*toppings):
    print(f"The customer need the sandwich with the following toppings:")
    for topping in toppings:
        print(f"\t-{topping}")
        return toppings

make_sandwich('cheese','vegetables')
result = make_sandwich('pepper','romaine','cheese','chicken')
print(type(result))

The customer need the sandwich with the following toppings:
-cheese
The customer need the sandwich with the following toppings:
-pepper
<class 'tuple'>

(2)个人信息函数。注意最后一个形参为双星号 **user_info,如果函数有返回值,其返回值为字典。

**kwargs格式的形参,用于收集任意数量的关键字实参。

def build_profile1(last,first,**user_info):
    user_info['last_name'] = last
    user_info['first_name'] = first    #创建了user_info字典,用于存放字典。
    return user_info
user_porfile = build_profile1('wang','zejing',
                             age = 37,
                             weight = '160kg',
                             height = '175cm')
print(user_porfile)
print(type(user_porfile))

{'age': 37, 'weight': '160kg', 'height': '175cm', 'last_name': 'wang', 'first_name': 'zejing'}
<class 'dict'>

def car_profile(brand,model,**car_info):
    car_info['brand'] = brand
    car_info['model'] = model
    return car_info

car_profile = build_profile1('Honda','civic',color = 'blue',size = 'B')
print(car_profile)

{'color': 'blue', 'size': 'B', 'last_name': 'Honda', 'first_name': 'civic'}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354

推荐阅读更多精彩内容