TKU STAT × Python Basic

Function


Kristen Chan

Agenda


  • 內建函數 (Built-in Function)
  • 自訂函數 (Defining a Function)
  • 匿名函數 (Anonymous function)

Built-in Function

Built-in Function

Note : What's function

what's function

Built-in Function

Note : What's function

In [1]:
sum( range(1,101) )
Out[1]:
5050

Note

  • input : range(1,101)
  • Function : sum
  • output : 5050

Built-in Function

Review 學過了哪些Function

  • sum( x ) : 加總
  • list( x ) : 轉換 list
  • type( x ) : 查看資料型態
  • zip( x ) : 壓和兩個 list

Defining a Function

Defining a Function


Function

  • 執行某特定功能的程式
  • 語法
    def functionname( parameters ):
      "function_docstring"
      function_suite 
      return(expression)
    

Note

  • 宣告一個 functionname (自己定義的 function 名稱)
  • " " 中寫下 function_docstring ( function 的說明 )
  • 撰寫 function_suite (打算要這個 function 做什麼)
  • 宣告 return ( 想要輸出計算結果 )

Defining a Function


寫一個計算圓面積的函數

In [2]:
def Circle_Area(r):
    "輸入半徑,就會回傳圓面積"
    import math
    result = math.pi * r * r
    return result
In [3]:
Circle_Area(3)
Out[3]:
28.274333882308138
In [4]:
help(Circle_Area)
Help on function Circle_Area in module __main__:

Circle_Area(r)
    輸入半徑,就會回傳圓面積

Defining a Function


寫一個計算圓面積的函數(設定默認值)

In [5]:
def Circle_Area(r=3):
    ''' 
    輸入半徑,就會回傳圓面積 
    若沒有輸入,則會計算半徑為3的圓面積
    '''
    import math
    result = math.pi * r * r
    return result
In [6]:
Circle_Area()
Out[6]:
28.274333882308138
In [7]:
Circle_Area(5)
Out[7]:
78.53981633974483

Defining a Function


回傳多個值

在 return 後,將多個值用逗號隔開,就會回傳一個 tuple

In [8]:
def Area(side,length,width,r):
    ''' 
    此為計算正方形,長方形,圓 面積函數
    請依序輸入以下參數
    正方形邊長 : side
    長方形長和寬 : length,width
    圓半徑 : r
    '''
    import math
    square_result = side * side
    circle_result = math.pi * r * r
    rectangular_result = length * width
    return square_result, rectangular_result, circle_result
In [9]:
Area(5,4,3,5)
Out[9]:
(25, 12, 78.53981633974483)

Defining a Function

Note : 默認值補充

如果輸入的函數中有的需要被定義有的則有默認值時,在定義函數時必須將需要被定義的參數統一放在前面

In [10]:
def Area(side,r=3,length,width):
    ''' 
    此為計算正方形,圓,長方形 面積的函數
    請依序輸入以下參數
    正方形邊長 : side
    圓半徑 : r ,若不輸入圓半徑,則默認為3
    長方形長和寬 : length,width
    '''
    import math
    square_result = side * side
    circle_result = math.pi * r * r
    rectangular_result = length * width
    return square_result, circle_result, rectangular_result
  File "<ipython-input-10-cc9db21c2376>", line 1
    def Area(side,r=3,length,width):
            ^
SyntaxError: non-default argument follows default argument

Defining a Function

Note : 默認值補充

如果輸入的函數中有的需要被定義有的則有默認值時,在定義函數時必須將需要被定義的參數統一放在前面

In [11]:
def Area(side,length,width,r=3):
    ''' 
    此為計算正方形,長方形,圓 面積函數
    請依序輸入以下參數
    正方形邊長 : side
    長方形長和寬 : length,width
    圓半徑 : r ,若不輸入圓半徑,則默認為3
    '''
    import math
    square_result = side * side
    circle_result = math.pi * r * r
    rectangular_result = length * width
    return square_result, rectangular_result, circle_result
In [12]:
Area(5,4,3)
Out[12]:
(25, 12, 28.274333882308138)
In [13]:
Area(5,4,3,3)
Out[13]:
(25, 12, 28.274333882308138)

Exercise

Q. 設計一個可以計算 list 個數的程式

Note

  • 類似 計算 1 加到 100
  • 結果會與 len() 相同

Answers

In [14]:
def my_count( x ):
    ''' 
    輸入:一個想要計算的list
    回傳:該list的個數
    '''
    temp_count = 0
    for i in x :
        temp_count += 1
    return(temp_count)
In [15]:
my_count(range(1,101))
Out[15]:
100
In [16]:
len(range(1,101))
Out[16]:
100

Exercise

Q. 設計一個可以加總 list 的程式

Note

  • list 中的元素必須都是數值
  • 結果會與 sum() 相同

Answers

In [17]:
def my_sum( x ):
    ''' 
    輸入:一個想要計算的list
    回傳:該list的總和
    '''
    temp_total = 0
    for i in x:
        temp_total = temp_total+i
    return temp_total 
In [18]:
my_sum(range(1,101))
Out[18]:
5050
In [19]:
sum(range(1,101))
Out[19]:
5050

Defining a Function

Note : 例外處理

語法

try:
    欲執行的程式
except 例外名稱 as 變數: 
    例外發生時,要做什麼事
else:
    若欲執行的程式沒發生例外,則會執行這裡
finally:
    不管有沒有發生例外都會跑到的程式

Note 可將例外名稱存成一個變數,做額外處理

Defining a Function

Note : 例外處理

In [20]:
def my_sum( x ):
    ''' 
    輸入:一個想要計算的list
    回傳:該list的總和
    '''
    try:
        temp_total = 0
        for i in x:
            temp_total = temp_total+i
        return temp_total 
    except TypeError:
        return  print("list 必須全為數值")
In [21]:
score = [55,89,100,'99']
my_sum(score)
list 必須全為數值

Defining a Function

Note : 例外處理

將 Error message 也輸出

In [22]:
def my_sum( x ):
    ''' 
    輸入:一個想要計算的list
    回傳:該list的總和
    '''
    try:
        temp_total = 0
        for i in x:
            temp_total = temp_total+i
        return temp_total 
    except TypeError as e:
        error = "list 必須全為數值" + "\n" + 'Error message: ' + str(e)
        return  print(error)
In [23]:
score = [55,89,100,'99']
my_sum(score)
list 必須全為數值
Error message: unsupported operand type(s) for +: 'int' and 'str'

Defining a Function


Nested function

  • function 中還有一個 function
  • 語法
    def functionname( parameters ):
      def functionname( parameters ):
          "function_docstring"
          function_suite 
          return(expression)
      return(expression)
    

Exercise

Q. 設計一個可以計算 list 平均數的程式,並計算未來一週 Taipei 的平均溫度

In [24]:
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]

公式:$Mean=\frac{\sum_{i=1}^{n} x_i}{n}$

Note

  • 計算總和 : my_sum( )
  • 計算個數 : my_count( )

Answers

In [25]:
def my_mean( x ):
    ''' 
    輸入:一個想要計算的list
    回傳:該list的平均數
    '''
    def my_sum( x ):
        "Total"
        temp_total = 0
        for i in x:
            temp_total = temp_total+i
        return temp_total    
    def my_count( x ):
        "Count"
        temp_count = 0
        for i in x :
            temp_count += 1
        return(temp_count)   
    temp_mean = my_sum( x ) / my_count( x )
    return temp_mean
In [26]:
my_mean(Temperature_Taipei)
Out[26]:
22.857142857142858

Anonymous function

Anonymous function


Lambda function

  • 單行的函數
  • 不需要 def、return 的敘述
  • 語法
    functionname = lambda parameters : function_suite
    

Anonymous function


Review Define Function

In [27]:
def Cubic_Func(num):
    ''' 
    輸入一個數字,就會回傳該數字的三次方
    '''
    result = num ** 3
    return result
In [28]:
print( Cubic_Func(2) )
8

Anonymous function


Lambda function

Method1.

In [29]:
Cubic_Lambda = lambda num : num ** 3
In [30]:
print( Cubic_Lambda(2) )
8

Method2.

In [31]:
(lambda num : num ** 3)(2)
Out[31]:
8

Anonymous function


Lambda function

  • 通常會和這些函數一起使用
    • map( )
    • filter( )

Anonymous function


Note : map( fnction, sequence )

針對 sequence 裡的元素依序執行 function(元素) , 並將該元素執行後的結果輸出為 list

In [32]:
my_list = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10]
In [33]:
print( list( map( Cubic_Func, my_list ) ) )
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Note Define Function

Anonymous function


Note : map( fnction, sequence )

針對 sequence 裡的元素依序執行 function(元素) , 並將該元素執行後的結果輸出為 list

my_list = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10]
In [34]:
print( list( map( lambda num : num ** 3, my_list ) ) )
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Note Lambda function

Anonymous function


Note : filter( function, sequence )

針對 sequence 裡的元素執行 function(元素) , 並輸出結果為 True 的元素

Note

  • 輸出的形式取決於給定的 sequence
    e.g. string \ list \ tuple

Anonymous function


Note : filter( function, sequence )

針對 sequence 裡的元素執行 function(元素) , 並輸出結果為 True 的元素

my_list = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10]
In [35]:
def even(num):
    ''' 
    判斷輸入的數字是否是偶數;若是偶數則會輸出,否則不輸出
    '''
    return num % 2 == 0
In [36]:
print( list( filter( even, my_list ) ) )
[2, 4, 6, 8, 10]

Note Define Function

Anonymous function


Note : filter( function, sequence )

針對 sequence 裡的元素執行 function(元素) , 並輸出結果為 True 的元素

my_list = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10]
In [37]:
print( list( filter( lambda num : num % 2 == 0, my_list ) ) )
[2, 4, 6, 8, 10]

Note Lambda function