1.定义函数
def + 函数名() + 冒号
2.向函数传递信息在函数定义时在()内添加
3.传递实参
(1)位置实参
最简单的关联方式是基于实参的顺序
(2)关键字实参
传递给函数的名称—值对,直接在实参中将名称和值关联起来了
如:
def pets(animal_type,animal_name): //函数定义
pets(animal_type = ‘dog’,animal_name = ‘harry’) //调用函数
(3)默认值
在函数定义时给形参指定默认值,如果调用函数中给形参提供了实参时, Python将使用指定的实参值; 否则 将使用形参的默认值。 因此, 给形参指定默认值后, 可在函数调用中省略相应的实参。
注 :Python将这个实参视为位置实参, 这个实参将关联到函数定义中的第一个形参,所以当实参传递给的不是第一个形参时,采用关键字实参
(4)返回简单值return
调用返回值的函数时, 需要提供一个变量, 用于存储返回的值。
print(变量名)
(5)让实参变成可选的
函数定义时给可选实参指定一个默认值:“空字符串”
用if判断是否有可选实参
(6)返回字典
def make_album(singer_name,album_name):
grate = {'singer':singer_name,'album':album_name}
return grate
momo = make_album('momo','fine')
mina = make_album('mina','ugly')
sana = make_album('sana','peace')
print(momo)
print(mina)
print(sana)
def make_album(singer_name,album_name,num = ' '):
'''创建一个描述音乐专辑的字典'''
music = {'singer':singer_name,'album':album_name}
if num:
full_word = singer_name + ' ' + album_name + ' ' + str(num)
else:
full_word = singer_name + ' ' + album_name
return full_word.title()#函数返回
momo = make_album('momo','fine',25)
mina = make_album('mina','ugly')
sana = make_album('sana','peace')
print(momo)
print(mina)
print(sana)
字典中存储singer_name的值的键为singer
(7)函数和while结合使用
ef get_formatted_name(first_name,last_name):
'''返回整洁的姓名'''
full_name =first_name + ' ' + last_name
return full_name.title()
while True:
print("\nPlease tell me your name: ")
print("(enter 'q' at any time 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("\nHello, " + formatted_name + "!")
(8)传递列表
将函数定义成接受一个名字列表, 并将其存储在形参names 中
(9)在函数中修改列表
def print_models(unprint_designs,completed_models):
'''
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表completed_models中
'''
while unprint_designs:
current_design = unprint_designs.pop()
#模拟根据设计制作3D打印模型的过程
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)
unprint_designs = ['iphone','robot','dodecahedron']
completed_models= []
print_models(unprint_designs,completed_models)
show_completed_models(completed_models)
10)禁止函数修改列表
切片表示法[:] 创建列表的副本,(9)中unprint_designs最终会变成空列表,如果想要列表不为空,则调用函数时传进unprint_designs的副本
print_models(unprint_designs[:],completed_models)
def show_magicians(magicians):
for magician in magicians:
print(magician)
def make_great(magicians,great_magicians):
while magicians:
magician = magicians.pop()
great_magicians.append(magician + ' the Great')
print("--------显示结果-------")
for great_magician in great_magicians:
print(great_magician)
magicians = ['john','cindy','sarah','mike']
great_magicians = []
show_magicians(magicians)
make_great(magicians[:],great_magicians)
print(magicians)
(10)传递任意数量的实参
形参为带有*的空元组
de