七、函数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

(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'}

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'}

你可能感兴趣的:(七、函数2(2022-04-12))