Python3 学习笔记(八)函数(下)

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')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值