python函数定义及应用(2)
#结合使用函数和while循环
#例子 向输入的人打招呼,按q退出程序
'''def get_formatted_name(first_name,last_name):
full_name=f"{first_name}{last_name}"
return full_name.title()
while 1:
print("n请告诉我你的名字:")
print("(enter 'q' to quit)")
f_name=input("first name:")
if f_name=='q':
break
l_name=input("last name")
if l_name=='q':
break
formatted_name=get_formatted_name(f_name,l_name)
print(f"nHello,{formatted_name}!")'''
#在函数中修改列表和传递列表
#例子 像每个列表中的人发出问候
'''def greet_users(names):
for name in names:
print(f"hello,{name.title()}")
usernames=['a','b','c']
greet_users(usernames)'''
#首先创建—个列表,其中包含一些要打印的设计,模拟打印每个设计,直到没有需要打印的射击位置
#打印每个设计之后,都将其移到新列表中,然后显示所有打印好的设计
'''def print_models(unprint_designs,completed_models):
while unprint_designs:
current_design=unprinted_designs.pop()
print(f"printing_model:{current_design}")
completed_models.append(current_design)
def show_completed_models(completed_models):
print("n下列模型被打印过:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs=['a','b','c']
completed_models=[]
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)'''
#此时原列表变成了空列表,如果想保留原列表需将倒数第二条命令改为print_models(unprinted_designs[:]#切片,completed_models)
#传递任意数量的实参
'''def make_pizza(*toppings):#此处定义了一个形参,若输入实参时有多个则会报错,此时需要在
#形参前加一个*,python会将其作为一个元组,收录后续输入的实参。
print(toppings)
make_pizza('蘑菇')
make_pizza('蘑菇','青椒')'''
#使用任意数量的关键字实参
'''def build_profile(first,last,**user_info):#两个*生成字典
#形参**user_info中的两个星号让 Python创建一个名为user_info的空字典,
#并将收到的所有名称值对都放到这个字典中。在这个函数中,
#可以像访问其他字典那样访问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)'''
#将该函数存储在模块中(与matlab相同,先把设定好的函数保存,重新打开新文件,使用import(保存函数的文件名)
#就可以使用此文件中的函数引用格式为:文件名.函数名(参数),也可以直接from 函数文件名 import 函数名,
#引用时不需要再加文件名。
#使用as给函数指定别名 函数名 as 别名
#使用as给模块指定别名 import 模块名 as 别名
#导入模块中的所有函数 from 模块名 import *