3-Python 函數(2)

本章概要:
  1、函數基礎
  2、深入理解函數
  3、綜合練習


1、函數基礎

</br>課程概要:
  理解函數
  定義函數
  調用函數
  函數文檔

一、理解函數

函數這個數學名詞是萊布尼茨在1694年開始使用的。

二、定義函數

1、Python 函數格式

def 函數名(參數1, 參數2,  ..., 參數n):
    函數體(語句塊)

2、函數的命名方式

三、調用函數

1、降低編程的難度,通常將一個復雜的大問題分解成一系列更簡單的小問題,然后將小問題繼續(xù)劃分成更小的問題,當問題細化足夠簡單時,就可以分而治之。

2、代碼重用

3、return 語句

def add_function(x, y):
    '''
    This is a function that adds x and y
    '''

    return x+y

if __name__=="__main__":
    a=4
    b=9
    c=add_function(a, b)

    print "a+b={0}+{1}={2}".format(a, b, c)
def add_function(x, y):
    '''
    This is a function that adds x and y
    '''

    return x+y

if __name__=="__main__":
    a=4
    b=9
    c=add_function(x=a, y=b)

    print "a+b={0}+{1}={2}".format(a, b, c)
def add_function(x, y):
    '''
    This is a function that adds x and y
    '''

    return x+y

if __name__=="__main__":
    a="py"
    b="thon"
    c=add_function(a, b)

    print "a+b={0}+{1}={2}".format(a, b, c)
# 斐波那契數列
def fibs(n):
    '''
    This is the Fibonacci sequence.
    '''
    result=[0, 1]
    for i in range(n-2):
        result.append(result[-2]+resultp[-1])
    return result

if __name__=="__main__":
    lst=fibs(10)
    print lst
#  返回多個值
def my_fun():
    return 1, 2, 3

b, c, d=my_fun()

四、函數文檔

1、程序在大多數情況下是給人看的,只是偶爾被機器執(zhí)行。

2、使用function.__doc__查看函數文檔


2、深入理解函數

課程概要:
  參數和變量
  參數收集和傳值
  特殊函數

一、參數和變量

# 函數就是對象
def foo(a, b):
    return a+b

p=foo
print p(4,5)

1、按引用傳遞參數

# 按引用傳遞
def foo(a, b):
    return a+b

x, y=3, 4
foo(x, y)

2、全局變量和局部變量

x=2    #  外部變量,但不是全局變量

def foo(a, b):
    x=9    #  局部變量
    print "This x is in the fun:",x
def bar():
    global x    #  全局變量
    x=9
    print "This x is in the fun:",x

3、命名空間

二、函數收集和傳值

1、收集方式一:*args

def foo(*args):
# args  接收參數生成的是元組
    print args

foo(1, 2, 3)
def foo(x, *args):
    print "x:",x
    print "args:",args

foo(1, 2, 3)

2、收集方式二:**kargs

def foo(* *kargs):
#  kargs 接收參數生成的是字典
    print kargs
  
foo(a=1, b=2, c=3)
#foo(1, 2, 3) 在這個函數里這樣傳是錯誤的
def foo(x, * args, * *kargs):
    print x
    print args
    print kargs

foo(1)
foo(1, 2)
foo(1, 2, 3)
foo(1, 2, 3, name="Li Sn")

3、另一種傳值方式

def foo(x, y):
    return x+y

bars= 2, 3
# *bars傳進去是元組(2, 3)
foo(*bars)
def book(author, name):
    print "{0} has a book:{1}".format(author, name)

bars={"name":"Learn Python", "author":"Boss"}

4、zip()補充

colors=["red", "green", "blue"]
values=[124, 23, 6, 100]
zip(colors, values)
# 沒有匹配的對象的100則會被拋棄
dots=[(1, 2), (3, 4), (5, 6)]
x, y=zip(*dots)
seq= range(1, 10)
zip(* [iter(seq)]*3)

#其實就是下面這個實現功能
x=iter(range(1, 10))
zip(x, x, x)

嘗試一下zip(* [iter(seq)]*2),看看結果是什么-。-

三、特殊函數

lambda
  map
  reduce
  filter

1、lambda

def foo(x):
    x+=3
    return x
n=range(10)
s=[i+3 for i in n]
lam=lambda x:x+3
n2=[]
for i in n2:
    n2.append(lam(i))
g=lambda x, y: x+y
g(3,4)

2、map

def foo(x):
    x+=3
    return x

n=range(10)
map(foo, n)
map(lambda x:x+3, n)
lst1=[1, 2, 3, 4, 5]
lst2=[6, 7, 8, 9, 10]

map(lambda x, y: x+y, lst1, lst2)

3、reduce

lst1=[1, 2, 3, 4, 5]
lst2=[6, 7, 8, 9, 10]

reduce(lambda x, y: x+y, lst1, lst2)

4、filter

n=range(-5,5)
filter(lambda x: x>0, n)

3、綜合練習

練習1:遞歸
  練習2:解方程
  練習3:統(tǒng)計考試成績
  練習4:找素數

一、遞歸

# 遞歸

def fib(n):
    '''
    This is Fibonacci by Recursion.
    '''
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fib(n-1)+fib(n-2)

if __name__=="__main__":
    f=fib(10)
    print f

二、解方程

# 解方程

from __future__ import division
import math

def quadratic_equation(a, b, c):
    delta= b*b-4*a*c
    if delta < 0:
        return False
    elif delta==0:
        return -(b/(2*a))
    else:
        sqrt_delta= math.sqrt(delta)
        x1=(-b + sqrt_delta)/(2*a)
        x2=(-b - sqrt_delta)/(2*a)
        return x1, x2

if __name__=="__main__":
    print "a quadratic equation: x^2 + 2x + 1=0"
    coefficients=(1, 2, 1)
    roots= quadratic_equation(*coefficients)
    if roots:
        print "the result is : ", roots
    else:
        print "this equation has no solution."

三、統(tǒng)計考試成績

# 統(tǒng)計考試成績

from __future__ import division

def average_score(scores):
    '''
    統(tǒng)計平均分
    '''
    score_values=scores.values()
    sum_scores=sum(score_values)
    average=sum_scores/len(score_values)
    return average

def sorted_score(scores):
    '''
    對成績從高到低排序
    '''
    score_lst=[(scores[k], k) for k in scores]
    sort_lst=sorted(score_lst, reverse=True)
    return [(i[1], i[0]) for i in sort_lst]

def max_score(scores):
    '''
    成績最高的姓名和分數
    '''
    lst=sorted_score(scores)
    max_score=lst[0][1]
    return [(i[1], i[0]) for i in lst if i[1]==max_score]

def min_score(scores):
    '''
    成績最低的姓名和分數
    '''
    lst=sorted_score(scores)
    min_score=lst[len(lst)-1][1]
    return [(i[1], i[0]) for i in lst if i[1]==min_score]

if  __name__=="__main__":
    examine_scores={"google":98, "facebook":99, "baidu":52, "alibaba":80,
                    "yahoo":49, "IBM":70, "amazon":99, "apple":99}

    ave=average_score(examine_scores)
    print "the average score is: ", ave

    sor=sorted_score(examine_scores)
    print "list of the scores: ", sor

    xueba =max_score(examine_scores)
    print "Xueba is : ", xueba

    xuezha=min_score(examine_scores)
    print "Xuezha is: ", xuezha

四、找素數

# 找素數

import math

def is_prime(n):
    '''
    判斷一個數是否是素數
    '''
    if n <= 1:
        return False
    for i in range(2, int(math.sqrt(n)+1)):
        if n%i ==0:
            return False
        return True

if __name__=="__main__":
    primes= [i for i in range(2, 100) if is_prime(i)]
    print primes

注意當自己寫函數時,需要注意的幾點:
1、盡量不要使用全局變量
2、參數是可變類型的數據,在函數中千萬不要輕易修改它
3、每個函數的目標和功能都要很單純,不要試圖一個函數做很多事情
4、函數的代碼函數要少
5、函數的獨立性要好

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容