python从入门到实践第八章----函数

'''
函数:
del 函数名(完成任务所需的信息):
函数体
调用函数:
函数名(实参)
'''
def greet_user():
print('hello')
greet_user()
'''
向函数传递信息
'''
'''
实参:调用函数时传递给函数的信息
形参:函数完成其工作所需的一项信息
'''
def greet_user(user_name):
print('hello '+user_name.title()+'!')
greet_user('jesse')
'''
传递实参
1、位置实参:实参形参位置相同
2、关键字实参:传名称-值对
3、等效的函数调用
'''
def describe_pet(animal_type,pet_name):
print('\nI have a '+animal_type+'.')
print('my '+animal_type+'s name is '+pet_name.title()+'.') describe_pet('dog', 'pangpang')#位置实参 describe_pet('cat','harry') describe_pet(pet_name='willie',animal_type='dog')#关键字实参 ''' 默认值:简化函数调用,清楚指出函数的典型用法。函数调用时相应的实参可以省略。 ''' def describe_pet(pet_name,pet_type='dog'):#依然将其视为位置实参。 print('\nI have a ' + pet_type + '.') print('my ' + pet_type + 's name is ' + pet_name.title() + '.')
describe_pet(pet_name='willie')
describe_pet('willie')
print('--------')
'''
下列做法是错误的:
def describe_pet(pet_type='dog',pet_name):#依然将其视为位置实参。
print('\nI have a ' + pet_type + '.')
print('my ' + pet_type + '`s name is ' + pet_name.title() + '.')

describe_pet(pet_name='willie')会出现报错

describe_pet('willie')会出现报错。

'''
'''
注意:默认值使用时要把未设置的形参放在开头位置,已经设置了的形参放在后面。不然会报错。
'''
print('--------')
def describe_pet(pet_name,pet_type='dog'):#依然将其视为位置实参。
print('\nI have a ' + pet_type + '.')
print('my ' + pet_type + '`s name is ' + pet_name.title() + '.')
describe_pet('harry','hamster')
describe_pet(pet_name='harry',pet_type='hamster')
describe_pet(pet_type='hamster',pet_name='harry')
print('--------')
'''
返回值:return语句
'''
def get_formatted_name(first_name,last_name):
full_name = first_name+' '+last_name
return full_name.title()
musician = get_formatted_name('jimi','hendrix')#将函数返回的结果赋给变量musician
print(musician)
'''
让实参变成可选的:给形参指定一个默认值,让形参变得可选
'''
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('jimi','lee','hendrix')
print(musician)
print('-------')
def get_formatted_name(first_name,last_name,middle_name=''):
if middle_name == '':
full_name = first_name+' '+last_name
else:
full_name = first_name + ' ' + middle_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi','hendrix','lee')
print(musician)
'''
实现手动输入
active = True
while active:
a = input('first name:')
if a == 'quit':
active = False
break
b = input('middle name ')
c = input('last name')
musician = get_formatted_name(a,b,c)
print(musician)
'''

'''
返回字典:函数可以返回列表,字典,,,
返回字典的好处是可以在字典中存储很多信息,便于调用
'''
print('--------')
def build_person(first_name,last_name):
person = {'first':first_name,'last':last_name}
return person
musician = build_person('jimi','hendrix')
print(musician)
print('--------')
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','27')
print(musician)
'''print('--------')
def 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 + '!')
'''
'''
传递列表:'''
def greet_users(names):
for name in names:
msg = 'hello,'+name.title()+'!'
print(msg)
usersnames = ['hannah','ty','margot']
greet_users(usersnames)#传递列表
'''
在函数中修改列表:
'''
unprinted_designs = ['iphon case','robot pendant','dodecahedron']
completed_models = []
while unprinted_designs:
current_design = unprinted_designs.pop()
print('printing model:'+current_design)
completed_models.append(current_design)
print('\nThe following models have been printed:')
for completed_model in completed_models:
print(completed_model)
'''
用函数来写
'''
print('--------')
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_designs = ['iphon case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)
print('--------')
print(unprinted_designs)
'''
使用函数的好处:程序更容易扩展和维护,主程序清晰。
'''
'''
禁止函数修改列表:向函数传递列表的副本,这样修改值影响副本而不影响原件。
切片表示法创建列表副本:list_name[:]
但是建副本,传递副本会占用内存。
'''
unprinted_designs = ['iphon case','robot pendant','dodecahedron']
completed_models = []
while unprinted_designs:
current_design = unprinted_designs.pop()
print('printing model:'+current_design)
completed_models.append(current_design)
print('\nThe following models have been printed:')
for completed_model in completed_models:
print(completed_model)
print('--------')

函数的方式来写#

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_designs = ['iphon case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs[:],completed_models)#传递列表副本#
show_completed_models(completed_models)
print('--------')
print(unprinted_designs)
'''
传递任意数量的实参:形参名中的让python创建一个名为topping的空元组。
python将实参封装在一个元组中。
'''
print('--------')
def make_pizza(
toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mashrooms','green peppers','extra cheese')

print('--------')
def make_pizza(toppings):
print('\nmaking a pizza with a following toppings:')
for topping in toppings:
print(topping)
make_pizza('pepperoni')
make_pizza('mashrooms','green peppers','extra cheese')
'''
结合使用位置实参和任意数量实参:传递不同类型的实参时,将接纳任意数量的实参的形参放在最后。
位置实参——>关键字实参——>任意实参
'''
def make_pizza(size,
toppings):
print('\nmaking a '+str(size)+'-inch pizza with a following toppings:')
for topping in toppings:
print('-' + topping)
make_pizza(16,'pepperoni')
make_pizza(12,'mashrooms','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='princeto',field='physics')
print(user_profile)
'''
将函数存储在模块中
函数的好处是将代码块与主程序分离便于程序的阅读与修改
将函数存储在被称为模块的独立文件中,再将模块导入主程序。这样做的好处是隐藏程序代码细节,将重点放在
程序的高级逻辑上。还可以在众多不同的程序中重用函数避免重复写函数。
'''
'''
导入整个模块:import 模块名
'''
import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushroom','green peppers','extra cheese')
'''
导入特定函数:
from model_name import function_name
from model_name import function_name1,function_name2
'''
print('--------')
from pizza import make_pizza
make_pizza(16,'pepperoni')#直接写函数名
make_pizza(12,'mushroom','green peppers','extra cheese')
'''
使用as给函数指定别名
'''
print('--------')
from pizza import make_pizza as mp #将make_pizza函数指定别名为mp
mp(16,'pepperoni')
mp(12,'mushroom','green peppers','extra cheese')
'''
使用as给模块指定别名
'''
print('--------')
import pizza as p
p.make_pizza(16,'pepperoni')
p.make_pizza(12,'mushroom','green peppers','extra cheese')
'''
导入模块中的所有函数
'''
from pizza import *#一般不这样用
make_pizza(16,'pepperoni')
make_pizza(12,'mushroom','green peppers','extra cheese')

你可能感兴趣的:(python从入门到实践第八章----函数)