自学Python笔记-第八章函数以及课后代码(下)

函数(下)

总结:学习了

如何编写函数,以及如何传递实参,让函数能够访问其工作需要的信息。

如何使用位置实参和关键字实参,以及如何接受任意数量实参。

显示输出的函数和返回值的函数

如何将函数同列表、字典 、if语句和while循环结合起来使用

如何将函数储存在称为模块的独立文件中,让程序文件更简单、更易于理解。

学习了函数编写指南,遵循这些指南可让程序始终结构良好,并对你和其他人来说易于阅读。

 

传递列表

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

在函数中修改列表

将列表传递给函数后,函数就可以对其值进行修改,并且修改是永久性的

使用函数的程序比起未使用函数的程序,组织更为有序。完成大部分工作的代码都移到了函数中,让主程序更容易理解。只要看看主程序,你就知道这个程序的工能容易看清楚得多。

禁止修改函数列表

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

要将列表的副本传递给函数,可以这么做: func(name[:])

切片表示法 [:] 创建列表副本。

虽然向函数传递列表的副本可保留原始列表的内容,但除非有充分的理由需要传递副本,否则还是应该将原始列表传递给函数,因为让函数使用现成列表可以避免花时间和内存创建副本,从而提高效率,在处理大型列表时尤其如此。

 

 

传递任意数量的实参

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

例子:def func(*toppings):

  *toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。

注意,Python将实参封装到一个元组中,即便函数只收到一个值也如此。

 

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

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

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


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

 

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

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


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

函数build_profile()的定义要求提供姓名,同时允许用户根据需要提供任意数量的名称-值对。

形参**user_info 中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有名称-值对都封装到这个字典中。在这个函数中,可以像访问其他字典一样访问user_info中的名称-值对

在这里,返回的字典包含用户的名和姓,还有求学的地方和所学专业。

 

将函数储存在模块中

函数的有点之一是,使用它们可将代码块与主程序分离。通过给函数指定描述性名称,可让主程序容易理解得多。

更进一步,将函数储存在被称为模块的独立文件中,再将模块导入到主程序中。

import语句允许在当前运行的程序文件中使用模块中的代码。

 

导入整个模块

要让函数是可导入的,得先创建模块。模块是扩展名为.py的文件,包含要导入到程序中的代码。

先创建pizza.py 里面包含函数make_pizza(size, *toppings)

再创建making_pizzas.py

其中代码如下:

import pizza

pizza.make_pizza(16, 'qwe')
pizza.make_pizza(22, 'wer', 'asd', 'fsa')

 

导入特定的函数

导入语法如下

from module_name import function_name

通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数。

from module_name import function_name, function2

 

使用as给函数指定别名

如果导入函数的名称导致与程序中现有的名称冲突,或函数的名称太长,可指定简短而独一无二的别名-类似于外号。

from module_name import function_name as fun1

 

使用as给模块指定别名

同理

import pizza as p

导入模块中所有函数

使用星号(*)运算符可以让Python导入模块中的所有函数

from pizza import *

一般只用在自己写的函数。因为别人的代码,你不知道写了上面。可能会冲突。

 

函数编写指南

应该给函数指定描述性名称,且只在其中使用小写字母和下划线。

每个函数应该包含简要地阐述其功能的注释。

 

动手试一试

8-9魔术师

def show_magicians(magician_names):
    for magician_name in magician_names:
        print(magician_name)


names = ['hyk', 'qwe', 'sfa']
show_magicians(names)

8-10了不起的魔术师

def show_magicians(magician_names):
    for magician_name in magician_names:
        print(magician_name)


def make_great(names, completed_names):
    while names:
        current_name = names.pop()
        completed_names.append(current_name + ' the Great')


people_names = ['hyk', 'qwe', 'sfa']
completed_names = []

make_great(people_names, completed_names)
show_magicians(completed_names)

8-11不变的魔术师

def show_magicians(magician_names):
    for magician_name in magician_names:
        print(magician_name)


def make_great(names, completed_names):
    while names:
        current_name = names.pop()
        completed_names.append(current_name + ' the Great')


people_names = ['hyk', 'qwe', 'sfa']
completed_names = []

make_great(people_names[:], completed_names)
show_magicians(completed_names)
show_magicians(people_names)

下面我贴的是原文代码,他的代码比我聪明,我输了。呜呜

def show_magicians(magicians):
    """Print the name of each magician in the list."""
    for magician in magicians:
        print(magician)

def make_great(magicians):
    """Add 'the Great!' to each magician's name."""
    # Build a new list to hold the great musicians.
    great_magicians = []

    # Make each magician great, and add it to great_magicians.
    while magicians:
        magician = magicians.pop()
        great_magician = magician + ' the Great'
        great_magicians.append(great_magician)

    # Add the great magicians back into magicians.
    for great_magician in great_magicians:
        magicians.append(great_magician)

    return magicians

magicians = ['Harry Houdini', 'David Blaine', 'Teller']
show_magicians(magicians)

print("\nGreat magicians:")
great_magicians = make_great(magicians[:])
show_magicians(great_magicians)

print("\nOriginal magicians:")
show_magicians(magicians)

8-12三明治

def make_pizza(*toppings):
    print("\n顾客点的三明治加的材料有:")
    for topping in toppings:
        print("- " + topping)


make_pizza('西瓜')
make_pizza('火腿', '番茄')
make_pizza('西瓜', 'huotui', 'fanqie')

8-13用户简介

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


user_profile = build_profile('albert', 'einstenin',
                             location='princeton',
                             field='physics',
                             telephone='123456789')
print(user_profile)

8-14汽车

def make_car(manufacturer, model, **options):
    car_information = {
        'manufacturer': manufacturer.title(),
        'model': model.title()
    }
    for key, value in options.items():
        car_information[key] = value

    return car_information


car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)

8-15,8-16,8-17

都是模块调用的知识,跟着书操作一边就行,很简单。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值