传递列表
def greet_users(names):
for name in names:
mag = "Hello, " + name.title() + "!"
print(mag)
user_names = ['hannah', 'bob', 'margot']
greet_users(user_names)
运行结果:
Hello, Hannah!
Hello, Bob!
Hello, Margot!
1. 在函数中修改列表
# 创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止,打印后移至completed_models中
while unprinted_designs:
current_design = unprinted_designs.pop()
# 模拟根据设计制作打印模型的过程
print("Printing model: " + current_design)
completed_models.append(current_design)
# 显示打印好的模型
print("nThe following models have been printed:")
print(completed_models)
运行结果:
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
['dodecahedron', 'robot pendant', 'iphone case']
用函数如何表达上述代码的意思呢?
def print_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):
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)
当print_models函数调用之后,列表completed_models已经不是最初定义的空,所有列表unprinted_designs中的元素已转移至列表completed_models,接下来调用show_completed_models函数就将列表completed_models中的元素都打印出来。
2. 禁止函数修改列表
上述的例子中print_models函数调用之后,列表unprinted_designs中的元素均已移除,此时的列表为空。但若想保留列表中的元素呢?
print_models(unprinted_designs[:], completed_models)
用切片法 [ : ] 创建列表副本,函数调用时使用的是列表的副本,而不是列表本身,此时函数中对列表做的修改不会影响到列表unprinted_designs。