每日一句:沉思的人有一个目标,幻想的人却没有。
传递列表
def greet_users(names): """向列表中的每位用户都发出简单的问候""" for name in names: msg="Hello, "+name.title()+"!" print(msg) usernames=[‘hannah‘,‘ty‘,‘margot‘] greet_users(usernames) # 指定整个列表为一个实参,传递给形参,存储在names中
# 创建列表,存储需要打印的文件 unprinted_designs=[‘iphone case‘,‘robot pendant‘,‘dodecahedron‘] completed_models=[] # 模拟打印的每一个文件,知道没有需要打印的 # 把打印好的放到completed_models中, while unprinted_designs: current_design=unprinted_designs.pop() # 模拟根据设计制作3D打印模型的过程 print("Print model: "+current_design) completed_models.append(current_design) # 显示打印好的所有模型 print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
禁止函数修改列表
# 创建列表副本 # 无论副本如何修改,原列表都不会发生改变 # funcation_name(list_name[:])
传递任意数量的参数
def make_pizza(*toppings): """打印顾客点的所有配料""" print(toppings) make_pizza(‘pepperoni‘) make_pizza(‘mushrooms‘,‘green peppers‘,‘extra cheese‘) # *toppings 创建一个空元祖来存储传递进来的实参
def make_pizza(*toppings): """概述要制作的披萨""" print("\nMaking a pizza with the following toppings:") for topping in toppings: print("- "+topping) make_pizza(‘pepperoni‘) make_pizza(‘mushrooms‘,‘green peppers‘,‘extra cheese‘) # *toppings 创建一个空元祖来存储传递进来的实参,遍历元组打印出来
结合使用位置实参和任意数量实参
def make_pizza(size,*toppings): """概述要制作的披萨""" print("\nMaking a "+str(size)+"-inch pizza with the following toppings:") for topping in toppings: print("- "+topping) make_pizza(16,‘pepperoni‘) make_pizza(12,‘mushrooms‘,‘green peppers‘,‘extra cheese‘)
使用任意数量的关键字实参
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=‘princetion‘,field=‘physics‘) print(user_profile) # ‘albert‘,‘einstein‘与first,和last相对于
原文:https://www.cnblogs.com/python-study-notebook/p/12709294.html