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')

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容