函數:python
一次定義,屢次調用,函數能夠變相當作變量
函數的階段:函數
1.定義階段 spa
2調用階段blog
形參和實參:內存
定義階段的參數叫形參,調用階段的參數叫實參io
函數的幾種基本用法:function
#多變量class
def test(name,age): print("在下%s,今年%s,請問有何貴幹!"%(name,age)) a = test('趙日天','18') >>> 在下趙日天,今年18,請問有何貴幹! def test(name,age="18"): print("在下%s,今年%s,請問有何貴幹!"%(name,age)) a = test('趙日天') >>> 在下趙日天,今年18,請問有何貴幹!
# *args能夠傳入多個實參test
def test(a,*args): print(a) print(args) test('a',1,1,1,1) >>> a >>> 1,1,1,1,1 test(['a','b'],'a','b') >>> ['a', 'b'] >>> ('a', 'b')
#**kwargs:能夠傳入多個鍵值對變量
#當元組中只有一個元素時,必須加一個‘,’。 def test(a,*args,**kwargs): print(a) print(args) print(kwargs) test(1,['a','b','c'],**{'name':'老郭','age':23}) >>> 1 >>> (['a', 'b', 'c'],) >>> {'name': '老郭', 'age': 23}
eg:
小實例:分開打印
def test(*args, **kwargs): if args: print(args) if kwargs: print(kwargs) test(1,2,3,4,5,6,a=100,b=200) >>> (1, 2, 3, 4, 5, 6) >>> {'a': 100, 'b': 200}
# return:返回一個函數的執行結果,
# 而且return日後的代碼將不會被執行,return能夠返回任意數據類型
n=3 def test(x,y): return x + y res = test(1,2) if n == res: print('==') else: print('!=') >>> ==
def test(x,y): print(x + y) res = test(1,2) >>> 3
#函數的名字就是內存地址,而且函數的內存地址加()就是調用
def test(): n1 = 1 n2 = 2 n3 = 3 dict1 = {'name1':n1,'name2':n2, 'name3':n3} return dict1 print(test) >>> <function test at 0x0000021D5CE91F28>