天天看點

python中的函數1. 函數

1. 函數

python中的函數1. 函數
python中的函數1. 函數
python中的函數1. 函數
def sum(a,b):
    c=a+b
    return c
a=sum(5,6)
print(a)



def fun(num):
    odd=[]
    even=[]
    for i in num:
        if i%2:
            odd.append(i)
        else:
            even.append(i)
    return odd,even

print(fun([2,3,4,5,6,7,8,9]))
           

1.1 函數定義預設值參數

python中的函數1. 函數

1.2 函數的參數的定義

python中的函數1. 函數
python中的函數1. 函數
python中的函數1. 函數

可變的位置參數應用的時候傳回的是元組,可變的關鍵字參數應用的時候傳回的是是字典

注意:可變的位置參數和可變的關鍵字形參都隻能定義一個。定義多個的時候會發生報錯。

python中的函數1. 函數

1.3 遞歸函數

python中的函數1. 函數

1.4 斐波那契數列

def fib(n):
    if n==1:
        return 1
    elif n==2:
        return 1
    else:
        return fib(n-1)+fib(n-2)
print(fib(6))