Python學(xué)習(xí)記錄(10)

parameter ? 形式參數(shù) ? ? ??

argument ?? 實際參數(shù)


1. 函數(shù)

>>> def add(num1, num2):

result = num1 + num2

print(result)

>>> add(1,2)

3

2.? 默認(rèn)參數(shù)

>>> def SaySome(name='小甲魚', words='讓編程改變世界'):

print(name + '->' + words)

>>> SaySome()

小甲魚->讓編程改變世界

3. 收集參數(shù)

>>> def test(*parameter):

print('參數(shù)的長度是:',len(parameter))

print('第二個參數(shù)是:', parameter[1])

>>> test(1,'小甲魚', 3.14, 5, 7, 8)

參數(shù)的長度是: 6

第二個參數(shù)是: 小甲魚

>>> def test(*params, exp):

print('參數(shù)的長度是:',len(params),exp);

print('第二個參數(shù)是:',params[1]);

>>> test(1, '小甲魚', 3.14, 5, 7, exp = 8)

參數(shù)的長度是: 5 8

第二個參數(shù)是: 小甲魚



1.? 函數(shù)返回值

>>> def hello():

print('Hello FishC!')

>>> temp = hello()

Hello FishC!

>>> temp

>>> print(temp)

None

>>> def back():

return [1, '小甲魚', 3.14]

>>> back()

[1, '小甲魚', 3.14]

>>> def back():

return 1, '小甲魚', 3.14

>>> back()

(1, '小甲魚', 3.14)

2. 局部變量和全局變量

文件1:

def discount(price, rate):

? ? final_price = price * rate

? ? old_price = 50

? ? print('這里試圖打印局部變量:',old_price)

? ? return final_price

old_price = float(input('請輸入原價:'))

rate = float(input('請輸入折扣率:'))

new_price = discount(old_price, rate)

print('打折后的價格是:',new_price)

print('這里試圖打印全局變量old_price:',old_price)

運行結(jié)果:

請輸入原價:110

請輸入折扣率:0.8

這里試圖打印局部變量: 50

打折后的價格是: 88.0

這里試圖打印全局變量old_price: 110.0

>>>

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

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

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