美文网首页
2022-07-23 Python学习笔记11

2022-07-23 Python学习笔记11

作者: 中年大叔 | 来源:发表于2022-07-30 22:26 被阅读0次

一、总体计划:

开始时间:2022-07-13

计划完成时间:2022-08-12

计划每日完成量:15页/天,或0.7章/天

二、今日(2022-07-23)学习进度:

今日已学习13页,完成1章,日任务达标。

总体进度199页/460页,11章/20章。

三、学习笔记:

1、返回值,函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值返回值 。在函数中,可使用return 语句将值返回到调用函数的代码行。返回值让你能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序。

def get_formatted_name(first_name, last_name):      
      """返回整洁的姓名"""
      full_name = first_name + ' ' + last_name
      return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

输出结果:
Jimi Hendrix

2、让实参变成可选的,有时候,需要让实参变成可选的,这样使用函数的人就只需在必要时才提供额外的信息。可使用默认值来让实参变成可选的。

def get_formatted_name(first_name, last_name, middle_name=' '):      
      """返回整洁的姓名"""
      if middle_name:          
          full_name = first_name + ' ' + middle_name + ' ' + last_name
      else:          
          full_name = first_name + ' ' + last_name
      return full_name.title()
 musician = get_formatted_name('jimi', 'hendrix')  
      print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')  
      print(musician)

输出结果:
Jimi Hendrix
John Lee Hooker

3、返回字典,函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。例如,下面的函数接受姓名的组成部分,并返回一个表示人的字典。

def build_person(first_name, last_name):      
      """返回一个字典,其中包含有关一个人的信息"""
      person = {'first': first_name, 'last': last_name} 
      return person
musician = build_person('jimi', 'hendrix')
print(musician)

输出结果:
{'first': 'jimi', 'last': 'hendrix'}

4、传递列表,你经常会发现,向函数传递列表很有用,这种列表包含的可能是名字、数字或更复杂的对象(如字典)。将列表传递给函数后,函数就能直接访问其内容。下面使用函数来提高处理列表的效率。
假设有一个用户列表,我们要问候其中的每位用户。下面的示例将一个名字列表传递给一个名greet_users() 的函数,这个函数问候列表中的每个人。

def greet_users(names):     
       """向列表中的每位用户都发出简单的问候"""
      for name in names:          
        msg = "Hello, " + name.title() + "!"          
        print(msg)
usernames = ['hannah', 'ty', 'margot']  
greet_users(usernames)

输出结果:
Hello, Hannah!
Hello, Ty!
Hello, Margot!

5、在函数中修改列表,将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的,这让你能够高效地处理大量的数据。

def print_models(unprinted_designs, completed_models):
      """      
      模拟打印每个设计,直到没有未打印的设计为止
      打印每个设计后,都将其移到列表completed_models中
      """
      while unprinted_designs:          
          current_design = unprinted_designs.pop()
          
          # 模拟根据设计制作3D打印模型的过程
          print("Printing model: " + current_design)          
          completed_models.append(current_design)

def show_completed_models(completed_models):
      """显示打印好的所有模型"""      
      print("\nThe following models have been printed:")      
      for completed_model in completed_models:          
            print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']  
completed_models = []

print_models(unprinted_designs, completed_models)  
show_completed_models(completed_models)

6、禁止函数修改列表,有时候,需要禁止函数修改列表。为解决这个问题,可向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件。

function_name(list_name[:])
# 切片表示法[:] 创建列表的副本
print_models(unprinted_designs[:], completed_models)

7、传递任意数量的实参,有时候,你预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参。例如,来看一个制作比萨的函数,它需要接受很多配料,但你无法预先确定顾客要多少种配料。下面的函数只有一个形参*toppings ,但不管调用语句提供了多少实参,这个形参都将它们统统收入囊中。

def make_pizza(*toppings):
    """概述要制作的比萨"""    
    print("\nMaking a pizza with the following toppings:")    
    for topping in toppings:        
        print("- " + topping)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

输出结果:
Making a pizza with the following toppings:
- pepperoni

Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

8、结合使用位置实参和任意数量实参,如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

9、使用任意数量的关键字实参,有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况下,可将函数编写成能够接受任意数量的键—值对——调用语句提供了多少就接受多少。两个星号让Python创建空字典,并将收到的所有名称—值对都封装到这个字典中。

def build_profile(first, last, **user_info):      
    """创建一个字典,其中包含我们知道的有关用户的一切"""      
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():          
        profile[key] = value      
    return profile

user_profile = build_profile('albert', 'einstein', location='princeton',field='physics')
print(user_profile)

输出结果:
{'first_name': 'albert', 'last_name': 'einstein','location': 'princeton', 'field': 'physics'}

相关文章

网友评论

      本文标题:2022-07-23 Python学习笔记11

      本文链接:https://www.haomeiwen.com/subject/ieqcwrtx.html