赞
踩
本文代码是在jupyter中实现的,仅为了自我督促学习python之用。
8-15 打印模型:将示例 print_models.py 中的函数放在另一个名为 printing_functions.py 的文件中;在 print_models.py 的开头编写一条 import 语句,并修改这个文件以使用导入的函数。
主程序代码:
模块:printing_functions.py
def print_models(unprinted_designs, completed_models):
"""打印列表unprinted_designs中的每个元素,
并将所有元素重新储存在空列表completed_models中
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""将列表completed_models列表中的所有元素都打印出来"""
print("\nThe following models have been printed: ")
for completed_model in completed_models:
print(completed_model)
运行代码:
###导入模块中的所有函数###
from printing_functions import *
unprinted_designs = ['iphone case', 'robot pendant', 'dodecaedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
运行结果:
Printing model: dodecaedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
dodecaedron
robot pendant
iphone case
8-16 导入:选择一个你编写的且只包含一个函数的程序,并将这个函数放在另一个文件中。在主程序文件中,使用下述各种方法导入这个函数,再调用它:
————————————————————————————————
import module_name
from module_name import function_name
from module_name import function_name as fn
import module_name as mn
from module_name import
————————————————————————————————
主程序代码:
模块:pizza.py
def make_pizza(size, *toppings):
"""概述要制作的披萨"""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings: ")
for topping in toppings:
print("- " + topping)
运行代码:
【注】:主程序的代码已经事先编辑好了,并保存为pizza.py,此处直接用"import"调用即可。这样会使代码更加精炼,如果想要实际了解具体的运行过程,就要去看模块代码,一个模块里面往往包含了多个函数。
###导入整个模块### import pizza pizza.make_pizza(16, 'pepperon') ###导入整个模块并自定义模块名### import pizza as p p.make_pizza(14, 'mushrooms', 'green peppers') ###导入特定的函数### from pizza import make_pizza make_pizza(12, 'mushrooms', 'extra cheese', 'mushrooms') ###导入特定的函数并自定义函数名### from pizza import make_pizza as mp mp(15, 'pepperon', 'green peppers') ###导入模块中的所有函数### from pizza import * make_pizza(10, 'mushrooms', 'green peppers', 'extra cheese', 'pepperon')
运行结果:
Making a 16-inch pizza with the following toppings: - pepperon Making a 14-inch pizza with the following toppings: - mushrooms - green peppers Making a 12-inch pizza with the following toppings: - mushrooms - extra cheese - mushrooms Making a 15-inch pizza with the following toppings: - pepperon - green peppers Making a 10-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese - pepperon
8-17 函数编写指南:选择你在本章中编写的三个程序,确保它们遵循了本节介绍的函数编写指南。
答案(略)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。