一、返回简单值
def get_formatted_name(first_name,last_name):
fullname = first_name+' '+last_name
return fullname.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)
运行结果:
Jimi Hendrix
- 让实参变成可选的:这样使用函数的人就只需要在必要的时候才提供额外的信息。可使用默认值来让实参变成可选的。
def get_formatted_name(first_name,middle_name,last_name):
full_name = first_name + ' '+ middle_name + ' '+ last_name
return full_name.title()
musician = get_formatted_name('john','lee','hooker')
print(musician)
运行结果:John Lee Hooker
- 但不是所有人都有中间名,如果调用函数时只提供了姓和名,他将不能正常运行。为让中间名变成可选的,可给实参middle_name()指定一个默认值–空字符串,并在用户没有提供中间名时不使用这个参数。为了让get_formatted_name()在没有提供中间名时依然可行,可给实参middle_name指定一个默认值—空字符串,并将其移到形参列表的末尾
def get_formatted_name(first_name,last_name,middle_name=''):
if middle_name:
full_name = first_name + ' '+ middle_name + ' '+ last_name
else:
full_name = first_name + ' ' +last_name
return full_name.title()
musician = get_formatted_name('john','lee','hooker')
print(musician)
musician = get_formatted_name('jimi','hendrix')
print(musician)
运行结果:
John Hooker Lee
Jimi Hendrix
二、返回字典
def build_person(first_name,last_name):
1. person = {'first':first_name,'last':last_name}
2.return person
musician = build_person('jimi','hendrix')
print(musician)
运行结果:
{‘first’: ‘jimi’, ‘last’: ‘hendrix’}
-
函数build_person接受名和姓,并将它封装在字典中(见1)。存储first_name时,使用的键是‘first’,而存储last_name时使用的键是‘last’。最后返回表示人的整个字典(见2)
-
这个函数接受简单的文本信息,将其放在一个更合适的数据结构中,让你不仅能打印,还能以别的方式处理他们。当字符串‘jimi’和‘hendrix’被标记为姓和名。你可以轻松扩充这个函数,使其接受可选值,如中间名、职业或其他信息
-
下面的修改可以存储年龄
def build_person(first_name,last_name,age=''):
person = {'first':first_name,'last':last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi','hendrix',age = 27)
print(musician)
三、传递列表
def greet_users(names):
for name in names:
msg = "hello," + name.title() + "!"
print(msg)
username = ['hahah','ty','margot']
greet_users(username)
运行结果:
hello,Hahah!
hello,Ty!
hello,Margot!
1、在函数中修改列表
- 不使用函数的情况下
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
while unprinted_designs:
current_design = unprinted_designs.pop()#pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
print("Printing model:" + current_design)
completed_models.append(current_design)#append() 方法用于在列表末尾添加新的对象。
print("\nthe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
运行结果:
Printing model:dodecahedron
Printing model:robot pendant
Printing model:iphone case
the following models have been printed:
dodecahedron
robot pendant
iphone case
- 使用函数
在函数中修改列表是永久性的
def print_models(unprinted_designs,completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
print("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(completed_model)
unprinted_design = ['iphone','robot','dodecahedron']
completed_model = []
print_models(unprinted_design,completed_model)
show_completed_models(completed_model)
运行结果:
printing model:dodecahedron
printing model:robot
printing model:iphone
the following models have been printed:
dodecahedron
robot
iphone
2、禁止函数修改列表
有时候需要禁止函数修改列表。
要将列表的副本传递给函数,可以这样做:
function_name(list_name[:])
切片表示法[:]创建列表的副本。
四、传递任意数量的实参
有时候你预先不知道函数需要接受多少个参数,好在python允许函数从调用语句中收集任意数量的实参
def make_pizza(*toppings):#*toppings中的*让python创建一个名为toppings的空元组,
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
运行结果:
(‘pepperoni’,)
(‘mushrooms’, ‘green peppers’, ‘extra cheese’)
注:
形参名toppings中的是让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。
1、结合使用位置实参和任意数量的实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量的实参的形参放在最后。python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
def make_pizza(size,*toppings):
"""概述要做的pizza"""
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')
运行结果:
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
2、使用任意数量的关键字实参
有时候需要接受任意数量的实参,但预先不知道传递给函数德惠市什么样的信息。在这种情况下,可将函数编写成能够接受任意键-值对------调用语句提供了多少就接受多少
def build_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['firstname'] = first
profile['lastname'] = 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)
运行结果:
{‘firstname’: ‘albert’, ‘lastname’: ‘einstein’, ‘location’: ‘princeton’, ‘field’: ‘physics’}