Python3 学习笔记(八)函数(下)
参考书籍《Python编程:从入门到实践》【美】Eric Matthes
编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。
def make_sandwich(*materials):
for material in materials:
print(material)
print('\n')
make_sandwich('apple')
make_sandwich('apple', 'mushroom')
make_sandwich('apple', 'mushroom', 'cheese')
编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的信息,以及两个名称—值对,如颜色和选装配件。
def build_car(manufacturer, version, **car_information):
car = {
'manufacturer': manufacturer,
'version': version
}
for key, value in car_information.items():
car[key] = value
return car
newCar = build_car('subaru', 'outback', color='blue', tow_package=True)
print(newCar)
选择一个你编写的且只包含一个函数的程序,并将这个函数放在另一个文件中。在主程序文件中,使用各种方法导入这个函数,再调用它:
# hello_world.py
def say_hello(name):
print('Hello ' + name.title())
模块导入
# main.py
def say_hello(name):
print('Hello ' + name.title())
从模块中导入函数
# main.py
from hello_world import say_hello
say_hello('god')
从模块中导入函数并赋予别名
# main.py
from hello_world import say_hello as sh
sh('god')
导入模块赋予别名
# main.py
import hello_world as hw
hw.say_hello('god')
从模块中导入全部函数
# main.py
from hello_world import *
say_hello('god')