传递列表
def greet_users(names):
for name in names:
meg =f"Hello,{name.title()}
print(meg)
users_names =['jame' ,'curry' ,'davis']
greet_users(users_names)
在函数中修改列表,这种修改是永久性的
unprinted_designs = ['phone case' , 'robot pendant' , 'dodecahedron']
completed_models =[]
while unprinted_designs:
current_design = unprinted_designs.pop() #弹出末尾元素
print(f"Printing model:{current_design}")
complete_models.append(current_design)
print(complete_models)
print(unprinted_designs)
两个函数的运用:
def print_models(unprinted_design,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(conpleted_models)
print(f"\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_models)
unprinted_design =['phone case','robot pendant','dodecahedron']
completed_models =[]
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)
禁止函数修改列表
在函数定义的参数中对参数加切片表示法 [:] 。
completed_models =[]
def print_models(unprinted_design[:],completed_models):
while unprinted_designs:
current_design =unprinted_designs,pop()
completed_models.append(current_design)
unprinted_design =['phone case','robot pendant','dodecahedron']
print_models(unprinted_designs,completed_models)
print(completed_models)
print(unprinted_design)
传递任意数量实参(不管实参有多少个统统由*+变量名来接收)
def make_pizza(*toppings:):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
使用任意数量的关键字实参(**+变量名用来接收任意数量的键值对)
def build_profile(first,last,**user_info)
user_info['first_name'] =first
user_info['last_name'] =last
return user_info
user_profile =build_profile('lin','xiaojie',location ='shaoyang',filed ='software')
print(user_profile)
函数储存在模块中(import()函数)
将函数储存在称为模块的独立文件中,再将模块导入到主程序中。
导入整个模块
就相当于是C++中把函数的定义写在头文件,在源文件中对函数进行调用就行了。在C++中我们用#include<'头文件名‘>,在Python中我们直接用impot 函数名。在这里是导入那个文件中所有函数,根据用户需求来对其中的函数调用,
导入特定函数
from module_name import function_0 , function_1,function_2
从module_name这个模板中导入function_0、function_1、function_2这几个函数
from pizza import make_pizza
make_pizza(16,'pepper')
make_pizza(12,'mushroom','green peppers','extra cheese')
as跟换函数名、模块名
本身没有任何难点就是把名字给换一下。
from module_name improt function_name as fn
import module_name as mn
导入模块中的所有函数
from module_name import *