1 函数传递参数
def greet_users(names): """向列表中的每个用户都发处问候""" for name in names: msg = "Hello ," + name.title() + "!" print(msg) usernames = ['baker','xiaocui','xiaoding'] greet_users(usernames)
2 修改函数中的列表
unprinted_designs = ['iphone case' ,'robot pendant' , 'dodecahedron'] completed_models = [] while unprinted_designs: current_design = unprinted_designs.pop() print("Pringting model:" + current_design) completed_models.append(current_design) print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model) print(completed_models[:])
3 传递任意数量的实参-元祖
def make_pizza(*toppings): """打印顾客点的配料""" print(toppings) make_pizza('pepperoni') make_pizza('mushrooms','green peppers','extra cheese')
4 使用任意数量的关键字-字典
def build_profile(first, last, **user_info): """创建一个字典,其中包含我们知道的有关用户的一切""" profile = {} profile['first_name'] = first profile['last_name'] = last for key,value in user_info.items(): profile[key] = value return profile user_profile = build_profile('albert','einstein',location='princeton',field='physics') print(user_profile)
5 把函数储存在模块中
import pizza pizza.make_pizza(16,'pepperonis') pizza.make_pizza(12,'mushrooms','green peppers','extra cheese') from pizza import make_pizza make_pizza(17,'pepperonis') from pizza import make_pizza as mp mp(18,'pepperonis') import pizza as p make_pizza(19,'pepperonis') from pizza import * make_pizza(20,'pepperonis')
导入函数的各种用法