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