我正在阅读Eric Matthes撰写的“Python Crash Course”一书,我似乎在练习8-15时遇到了问题。
8-15说:“将示例print_models.py的函数放在一个名为printing_functions.py的单独文件中。在print_models.py的顶部写一个import语句,并修改该文件以使用导入的函数。< / p>
这是我的printing_functions.py模块的代码:
def print_models(unprinted_designs, completed_models):
"""Simulate printing each design, until none are left.
Move each design to completed_models after printing."""
while unprinted_designs:
current_design = unprinted_designs.pop()
# Simulate creating a 3D print from the design.
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
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)
这是我的练习代码8-15
import printing_functions as pf
pf.print_models(unprinted_designs, completed_models)
pf.show_completed_models(completed_models)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
当我运行此代码时,我能够收到与模块中相同的输出。但是我也收到并在底部显示错误,指出未定义'unprinted_designs'。但我明确将此变量定义在我的代码底部附近作为列表,所以我不明白为什么我收到此错误。
有没有人对我可能做错了什么有任何想法?任何反馈将不胜感激。谢谢你的时间。
答案 0 :(得分:1)
您大部分都做了正确的事情,但需要先分配变量才能使用它们。
此外,由于您已将功能分离/移动到模块,因此必须使用那些导入的功能,而变量仍保留在此模块中
import printing_functions as pf
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
pf.print_models(unprinted_designs, completed_models)
pf.show_completed_models(completed_models)
然后,删除另一个模块末尾的不必要的行。只有函数定义应该在那里