python---函數

函數特性:減少重複代碼,使程序變的可擴展,使程序變得易維護

1.定義函數
#定義函數
def func1():
    """test"""
    print("this is test")
    return 0

#定義過程                #通俗的說過程就是沒有返回的函數,但python會返回一個none
def func2():
    """test1"""
    print("this is test")
    
#調用函數
x = func1()
y = func2()

#打印函數返回值
print(x,y)
#0 None


2、函數返回值

#函數返回值作用:判斷該函數執行情況。其他程序有可能需要根據該返回值進行不同的操作

def test1():
    print("this is test")                       #返回none

def test2():
    print("this is test")
    return 0                                    #返回0

def test3():
    print("this is test")
    return 1,"hello",["a","b"],{"a":"b"}        #返回一個元組

x = test1()
y = test2()
z = test3()
print(x)
print(y)
print(z)


3、函數參數

#1.位置參數和關鍵字參數
def test1(x,y,z):
    print(x)
    print(y)
    print(z)

test1(1,2,3)        #位置參數,與順序有關
test1(y=2,z=3,x=1)  #關鍵字參數,與位置無關
test1(1,z=3,y=2)    #既有位置參數,又有關鍵字參數,位置參數不能再關鍵字參數前面

#2.默認參數
def test2(x,y=2):
    print(x)
    print(y)

test2(1)            #如果不指定y,則使用默認值,指定新值則用新值
test2(1,3)
test2(1,y=3)

#3.參數組

def test3(*args):       #將傳入值轉化成一個元組
    print(args)

test3(1,2,3,4,5)
test3(*[1,2,3,4,5])

#輸出
# (1, 2, 3, 4, 5)
# (1, 2, 3, 4, 5)

def test4(x,*args):
    print(x)
    print(args)
test4(1,2,3,4,5)

#輸出
# 1
# (2, 3, 4, 5)

def test5(**kwargs):        #將“關鍵字參數”轉化成一個字典
    print(kwargs)

test5(y=1,x=2,z=3)

#輸出
# {'y': 1, 'x': 2, 'z': 3}

def test6(name,age=18,**kwargs):
    print(name)
    print(age)
    print(kwargs)

test6("feng",y=1,x=2)
#輸出
# feng
# 18
# {'y': 1, 'x': 2}
test6("feng",23,y=1,x=2)
#輸出
# feng
# 23
# {'x': 2, 'y': 1}


4、局部變量與全局變量

name1 =  "fengxiaoli"        #全局變量,對所有函數生效,如果全局變量定義的是字符串或者數字,則在局部修改之後只對局部生效,\
def test():                 #對全局還是沒生效,如果全局變量定義的是字典,列表,集合,類,則在局部修改之後對全局也生效
    #global name             #在函數中聲明全局變量,慎用
    name1 = "cx"              #局部變量,只在該函數中生效
    print(name1)

test()
print(name1)
# 輸出:
# cx
# fengxiaoli

name2 = ["cx","fengxiaoli"]
def test2():
    name2[0] = "CX"
    print(name2)

test2()
print(name2)
# 輸出:
# ['CX', 'fengxiaoli']
# ['CX', 'fengxiaoli']


5、遞歸函數

#遞歸特性:必須有一個明確的結束條件。每次進入更深層次的遞歸,問題規模相比上次遞歸都應有所減少。遞歸效率不高
def calc(n):
    print(n)
    if int(n/2)>0:
        return (calc(int(n/2)))

calc(10)


6、高階函數

#變量可以指向函數,函數的參數能接收變量,那麼一個函數就可以接收另一個函數作爲參數,這種函數稱爲高階函數
def test(a,b,f):
    res = f(a)+f(b)
    print(res)
test(-5,3,abs)          #這裏的abs是一個求絕對值的函數


7、匿名函數

calc = lambda x:x*3

print(calc(3))


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章