一? 函數基本
def func1():print("hello world")return 1, "hello", ("wo", "ai"), ["ni", "da"], {"you": "xi"} # return 可以返回任意# 結果: (1, 'hello', ('wo', 'ai'), ['ni', 'da'], {'you': 'xi'}) # return func1 # 返回函數的內存地址# 結果: <function func1 at 0x7f32184adf28>print(func1())
?
# 總結:
#? 返回值數:=0,返回None
#? 返回值數:=1,返回對象object
#? 返回值數:>1,返回元組
?
二? 函數形參和實參
def test1(x, y): # x, y 叫做 形參print(x)print(y)test1(1, 2) # 1,2 叫做 實參 與形參位置一一對應 test1(x=1, y=2) # 打印結果一樣 test1(y=2, x=1) # 打印結果一樣 與形參順序無關 # test1(x=1, 2) # 報錯 關鍵參數是不能寫在位置參數前面的 test1(1, y=2) # 不報錯 # test1(1, x=1) # 報錯def test2(x, y, z):print(x, y, z)test2(1, y=2, z=3) test2(1, z=3, y=2) # 結果與上面一樣 #test2(1, x=1, z=2) # 報錯,x位置賦予了兩個值def test3(x, y=2): # y 是默認參數print(x, y)test3(1) # 打印 1,2 test1(1,3) #打印 1,3 test3(1, y=3) #打印 1,3# 注:默認參數的特點,在調用的時候,可有可無 # 用途:默認安裝軟件
?
?
三? 數組參數
def test4(*args): #*args === args = tuple([]) # 接受位置參數print(args) # 返回元組 test4(1,2,3,4) # 打印: (1,2,3,4) test4(*[1,2,3,4]) # 打印: (1,2,3,4)def test5(x, *args): # 混合參數print(x)print(args)test5(1,2,3,4,5,6) # 打印結果: # 1 # (2,3,4,5,6))
?
?
四? 字典參數
def test6(**kwargs): # 接受字典的形式, 把關鍵字參數,轉化為字典print(kwargs) # 返回字典 test6(name="sam", age=28) # 結果:{'name': 'sam', 'age': 28} test6(**{'name': 'sam', 'age': 28}) # 結果一樣def test7(name, **kwargs):print(name)print(kwargs)test7('sam') # 結果 # sam # {}# test7('sam', 'yong') # 報錯,因為只能接受一個位置參數, 而kwargs只接受關鍵字參數 test7('sam', name="sam", age=28) # 結果 # sam # {'name': 'sam', 'age': 28}def test7(name, age=12, **kwargs): #def test7(name, **kwargs, age=12): # 報錯print(name)print(age)print(kwargs)test7('sam', addr='beijing', phone=123456) # # 結果 # sam # 12 # {'addr': 'beijing', 'phone': 123456} test7('sam', age=3, addr='beijing', phone=123456) test7('sam', 3, addr='beijing', phone=123456) test7('sam', addr='beijing', phone=123456, age=3) # test7('sam',23, addr='beijing', phone=123456, age=3) # 報錯,age 多值錯誤 # 以上結果都一樣 # sam # 3 # {'addr': 'beijing', 'phone': 123456}def test8(name, age=12, *args, **kwargs):print(name)print(age)print(args)print(kwargs)test8('sam', age=3, addr='beijing', phone=123456) # 位置參數一定要寫在關鍵字參數的前面 # 結果 # sam # 12 # () # {'addr': 'beijing', 'phone': 123456}
?
?
五? 局部變量 和 全局變量
?
name = "sam" def func1():print(name) # name = "jey" # 程序會報錯 UnboundLocalError: local variable 'name' referenced before assignment func1()
# 結果
# sam
?
name = 'sam' def chname(name):print("before change name:", name)name = 'jey' # 這個變量的作用域只在這個函數中print("after change name:", name)chname(name) print(name) # sam 沒有變 # 結果 # before change name:sam # after change name:jey # sam
?
如果要在函數中修改全局變量,使用global 申明變量
name = 'gao' def testname():global name # 引用全局變量 最佳實踐 global 不要用print(name) # gaoname = 'shao'print(name) # shao testname() print(name) # shao 改變了
?
# 注:只有數字,字符串 不能再函數中改,但是,列表,字典,集合能改
names = ['sam', 'jey', 'snow']def test9():print(names)name[0] = 'sammy'print(names)test9() print(names) # 結果 # ['sam', 'jey', 'snow'] # ['sammy', 'jey', 'snow'] # ['sammy', 'jey', 'snow']
?