4. 传递列表
def greet_users(names):
"""向列表中的每位用户发出问候。"""
for name in names:
msg = f"Hello, {name.title()}"
print(msg)
usernames = ['hanks', 'jackson', 'jimmy']
greet_users(usernames)
4.1在函数中修改列表
在函数中对列表所做的任何修改都是永久性的
def print_models(unprinted_designs, completed_models):
"""
模拟打印每个设计,直到没有未打印的设计。
打印每个设计后,都将其移到列表completed_models中。
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"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(f"\t{completed_model}")
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
4.2 禁止函数修改列表
function_name(list_name[:])
向函数传递列表的副本,则不会修改原始数据。处理大量数据时慎用,创建副本占用时间和内存。
5. 传递任意数量的参数
def create_user(*fields):
"""打印用户的所有属性"""
for field in fields:
print(field)
create_user('tom', 'hanks', 33, 1.80, True)
形参名*field中的星号创建一个名为fields的空元组,并将收到的所有实参封装到元组中。
5.1 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
5.2 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
"""创建一个字典,其中包含我们知道的有关用于的一切。"""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
形参**user_info中两个星号创建了一个名为user_info的空字典,并将收到的所有名称值对都放入该字典中。
6. 将函数存储在模块中
函数与主程序分离:
(1)隐藏代码细节,将重点放在高层逻辑;
(2)在不同的程序中重用函数
(3)与其他程序员共享
6.1 导入整个模块
模块即扩展名为.py的文件
pizza.py
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print(f"\nMaking a {size}-inch pizza with the following topping:")
for topping in toppings:
print(f"- {topping}")
making_pizzas.py
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
6.2 导入特定的函数
from module_name import function_name
from module_name import function_0, function_1, function_2
示例
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
6.3 使用as给函数指定别名
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
6.4 使用as给模块指定别名
from pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
标签:函数,python,completed,models,user,print,make,pizza From: https://www.cnblogs.com/route/p/17538114.html最好只导入需要使用的函数