python從入門到實(shí)踐第八章----函數(shù)

'''
函數(shù):
del 函數(shù)名(完成任務(wù)所需的信息):
函數(shù)體
調(diào)用函數(shù):
函數(shù)名(實(shí)參)
'''
def greet_user():
print('hello')
greet_user()
'''
向函數(shù)傳遞信息
'''
'''
實(shí)參:調(diào)用函數(shù)時(shí)傳遞給函數(shù)的信息
形參:函數(shù)完成其工作所需的一項(xiàng)信息
'''
def greet_user(user_name):
print('hello '+user_name.title()+'!')
greet_user('jesse')
'''
傳遞實(shí)參
1、位置實(shí)參:實(shí)參形參位置相同
2、關(guān)鍵字實(shí)參:傳名稱-值對(duì)
3、等效的函數(shù)調(diào)用
'''
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')#位置實(shí)參 describe_pet('cat','harry') describe_pet(pet_name='willie',animal_type='dog')#關(guān)鍵字實(shí)參 ''' 默認(rèn)值:簡(jiǎn)化函數(shù)調(diào)用,清楚指出函數(shù)的典型用法。函數(shù)調(diào)用時(shí)相應(yīng)的實(shí)參可以省略。 ''' def describe_pet(pet_name,pet_type='dog'):#依然將其視為位置實(shí)參。 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('--------')
'''
下列做法是錯(cuò)誤的:
def describe_pet(pet_type='dog',pet_name):#依然將其視為位置實(shí)參。
print('\nI have a ' + pet_type + '.')
print('my ' + pet_type + '`s name is ' + pet_name.title() + '.')

describe_pet(pet_name='willie')會(huì)出現(xiàn)報(bào)錯(cuò)

describe_pet('willie')會(huì)出現(xiàn)報(bào)錯(cuò)。

'''
'''
注意:默認(rèn)值使用時(shí)要把未設(shè)置的形參放在開頭位置,已經(jīng)設(shè)置了的形參放在后面。不然會(huì)報(bào)錯(cuò)。
'''
print('--------')
def describe_pet(pet_name,pet_type='dog'):#依然將其視為位置實(shí)參。
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語(yǔ)句
'''
def get_formatted_name(first_name,last_name):
full_name = first_name+' '+last_name
return full_name.title()
musician = get_formatted_name('jimi','hendrix')#將函數(shù)返回的結(jié)果賦給變量musician
print(musician)
'''
讓實(shí)參變成可選的:給形參指定一個(gè)默認(rèn)值,讓形參變得可選
'''
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)
'''
實(shí)現(xiàn)手動(dòng)輸入
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)
'''

'''
返回字典:函數(shù)可以返回列表,字典,,,
返回字典的好處是可以在字典中存儲(chǔ)很多信息,便于調(diào)用
'''
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)#傳遞列表
'''
在函數(shù)中修改列表:
'''
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)
'''
用函數(shù)來寫
'''
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)
'''
使用函數(shù)的好處:程序更容易擴(kuò)展和維護(hù),主程序清晰。
'''
'''
禁止函數(shù)修改列表:向函數(shù)傳遞列表的副本,這樣修改值影響副本而不影響原件。
切片表示法創(chuàng)建列表副本:list_name[:]
但是建副本,傳遞副本會(huì)占用內(nèi)存。
'''
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('--------')

函數(shù)的方式來寫#

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)
'''
傳遞任意數(shù)量的實(shí)參:形參名中的讓python創(chuàng)建一個(gè)名為topping的空元組。
python將實(shí)參封裝在一個(gè)元組中。
'''
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')
'''
結(jié)合使用位置實(shí)參和任意數(shù)量實(shí)參:傳遞不同類型的實(shí)參時(shí),將接納任意數(shù)量的實(shí)參的形參放在最后。
位置實(shí)參——>關(guān)鍵字實(shí)參——>任意實(shí)參
'''
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')
'''
使用任意數(shù)量的關(guān)鍵字實(shí)參:能接受任意數(shù)量的形參,但預(yù)先不知道傳遞給函數(shù)的會(huì)是什么樣的信息
可將函數(shù)編寫成能夠接受任意數(shù)量的鍵值對(duì)。
形參名,表示創(chuàng)建一個(gè)形參名的空字典。并將所有接收到的名稱-值對(duì)封裝進(jìn)一個(gè)字典
'''
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)
'''
將函數(shù)存儲(chǔ)在模塊中
函數(shù)的好處是將代碼塊與主程序分離便于程序的閱讀與修改
將函數(shù)存儲(chǔ)在被稱為模塊的獨(dú)立文件中,再將模塊導(dǎo)入主程序。這樣做的好處是隱藏程序代碼細(xì)節(jié),將重點(diǎn)放在
程序的高級(jí)邏輯上。還可以在眾多不同的程序中重用函數(shù)避免重復(fù)寫函數(shù)。
'''
'''
導(dǎo)入整個(gè)模塊:import 模塊名
'''
import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushroom','green peppers','extra cheese')
'''
導(dǎo)入特定函數(shù):
from model_name import function_name
from model_name import function_name1,function_name2
'''
print('--------')
from pizza import make_pizza
make_pizza(16,'pepperoni')#直接寫函數(shù)名
make_pizza(12,'mushroom','green peppers','extra cheese')
'''
使用as給函數(shù)指定別名
'''
print('--------')
from pizza import make_pizza as mp #將make_pizza函數(shù)指定別名為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')
'''
導(dǎo)入模塊中的所有函數(shù)
'''
from pizza import *#一般不這樣用
make_pizza(16,'pepperoni')
make_pizza(12,'mushroom','green peppers','extra cheese')

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容