8 5 傳遞任意數量的實參及關鍵字引數

2021-10-06 20:51:38 字數 2874 閱讀 6952

# -*- coding:utf-8 -*-

#li hongliang 2023年06月05日

#8.5 傳遞任意數量的實參

#8.5.1 結合使用位置實參和任意數量實參:如果要讓函式接受不同型別的實參,必須在函式定義中將接納任意數量實參的形參放在最後。

#8.5.2 使用任意數量的關鍵字實參形參**user_info中的兩個星號讓python建立乙個名為user_info的空字典,並將收到的所有名稱—值對都封裝到這個字典中。在這個函式中,可以像訪問其他字典那樣訪問user_info中的名稱—值對

#8-12 三明治:編寫乙個函式,它接受顧客要在三明治中新增的一系列食材。這個

#函式只有乙個形參(它收集函式呼叫中提供的所有食材),並列印一條訊息,對顧客點

#的三明治進行概述。呼叫這個函式三次,每次都提供不同數量的實參。

defmake_pizza

(*toppings)

:#print(toppings) #列印結果是元組

print

("\n****** a pizza with the following toppings:"

)for topping in toppings:

print

("-"

+topping )

make_pizza(

'sweate'

,'vegetables'

,'fruit'

)make_pizza(

'chicken'

,'tomatoes'

)make_pizza(

'banana'

,'orange'

,'egg'

,'onion'

)#8-13 使用者簡介:複製前面的程式user_profile.py,在其中呼叫build_profile()來

#建立有關你的簡介;呼叫這個函式時,指定你的名和姓,以及三個描述你的鍵值對。

defbuild_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=

'princeton'

,field=

'physics'

)user_profile1 = build_profile(

'li'

,'hongliang'

,hobby =

'sing'

,sports =

'basketball'

,idol =

'yuquan'

)user_profile2 = build_profile(

'li'

,'jiaojiao'

,hobby =

'sing'

,sports =

'watching tv'

,idol =

'linjunjie'

)print

(user_profile)

print

(user_profile1)

print

(user_profile2)

#8-14 汽車:編寫乙個函式,將一輛汽車的資訊儲存在乙個字典中。這個函式總是接

#受製造商和型號,還接受任意數量的關鍵字實參。這樣呼叫這個函式:提供必不可少的

#資訊,以及兩個名稱—值對,如顏色和選裝配件。這個函式必須能夠像下面這樣進行呼叫:

#car = make_car('subaru', 'outback', color='blue', tow_package=true)

#列印返回的字典,確認正確地處理了所有的資訊。

defmake_car

(manufacturer,model,

**introduce)

: car_information =

car_information[

'manufacturers'

]= manufacturer

car_information[

'models'

]= model

for key,value in introduce.items():

car_information[key]

= value

return car_information

car = make_car(

'subaru'

,'outback'

,color=

'blue'

, tow_package=

true

)car1 = make_car(

'volvo'

,'t4'

,color=

'white'

, tow_package=

true

,engine =

'imported'

,price =

280000

)print

('\n'

)print

(car)

print

(car1)

8 5 傳遞任意數量的實參

8 12 三明治 編寫乙個函式,它接受顧客要在三明治中新增的一系列食材。這個 函式只有乙個形參 它收集函式呼叫中提供的所有食材 並列印一條訊息,對顧客點 的三明治進行概述。呼叫這個函式三次,每次都提供不同數量的實參。def sandwishes toppings for topping in top...

Python 函式傳遞任意數量的實參

案例 toppings 形參名中的星號讓python建立了乙個空元組,並將收到的所有值都封裝到這個元組中 defmake pizza toppings 列印顧客點的所有配料 print toppings make pizza pepperoni make pizza mushrooms green ...

python 給函式傳遞任意數量的實參

1.在預先不知道有多少個實參的情況下。可以使用如下操作,允許函式從呼叫語句中收集任意數量的實參。def function name test print test function name 1 function name 1 2 3 輸出結果 1 1 2 3 形參 test讓python 建立乙個...