Python × 資料分析

Function


Kristen Chan

Agenda


  • Defining a Function
  • Anonymous function

Defining a Function

Defining a Function


What's function

what's function

Defining a Function


What's function

Example

In [1]:
sum( range(1,101) )
Out[1]:
5050
  • input : range(1,101)
  • Function : sum
  • output : 5050

Note

學過了哪些Function

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

Defining a Function


Function

  • 執行某特定功能的程式
  • 語法
    def functionname( parameters ):
      "function_docstring"
      function_suite 
      return(expression)
    
  • 宣告一個 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

Note

默認值補充

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

In [8]:
def Area(side,r=3,length,width):
    ''' 
    此為計算正方形,圓,長方形 面積的函數
    請依序輸入以下參數
    正方形邊長 : side
    圓半徑 : r
    長方形長和寬 : length,width
    其中若不輸入圓半徑,則默認為3
    '''
    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-8-14df7367929a>", line 1
    def Area(side,r=3,length,width):
            ^
SyntaxError: non-default argument follows default argument

Note

默認值補充

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

In [9]:
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 [10]:
Area(5,4,3)
Out[10]:
(25, 12, 28.274333882308138)
In [11]:
Area(5,4,3,3)
Out[11]:
(25, 12, 28.274333882308138)

Exercise

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

提示 : 類似 計算 1 加到 100

Answers

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

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 [14]:
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]

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

試著定義兩個函數

  1. 計算總和 : my_sum( )
  2. 計算個數 : my_count( )

Answers

In [15]:
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 [16]:
my_mean(Temperature_Taipei)
Out[16]:
22.857142857142858

Anonymous function

Anonymous function


Lambda function

  • 單行的函數
  • 語法
    functionname = lambda parameters : function_suite
    

Anonymous function


Review

Define Function

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

Anonymous function


Lambda function

Method1.

In [19]:
Cubic_Lambda = lambda num : num ** 3
In [20]:
print( Cubic_Lambda(2) )
8

Method2.

In [21]:
(lambda num : num ** 3)(2)
Out[21]:
8
In [22]:
print( Cubic_Lambda(2) )
8

Anonymous function


Lambda function

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

Note

map( function, sequence )

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

In [23]:
my_list = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10]

Define Function

In [24]:
print( list( map( Cubic_Func, my_list ) ) )
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Note

map( function, sequence )

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

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

Lambda function

In [25]:
print( list( map( lambda num : num ** 3, my_list ) ) )
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Note

filter( function, sequence )

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

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

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

Define Function

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

Note

filter( function, sequence )

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

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

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

Lambda function

In [28]:
print( list( filter( lambda num : num % 2 == 0, my_list ) ) )
[2, 4, 6, 8, 10]