什麼是函式?

Python 的資料科學入門

Hillary Green-Lerman

Lead Data Scientist, Looker

函式就是一個動作

function-analogy

Python 的資料科學入門

程式中的函式

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_csv('letter_frequency.csv')

plt.plot(df.letter_index, df.frequency, label='Ransom')
plt.show()

函式會執行動作:

  • pd.read_csv() 將 csv 檔轉成 Python 裡的資料表
  • plt.plot() 將資料畫成折線圖
  • plt.show() 在新視窗顯示圖表
Python 的資料科學入門

Python 的資料科學入門

函式結構:函式名稱

function-anatomy

函式名稱

  • 以函式所屬的模組開頭(plt
  • 接著是函式名稱(plot
  • 名稱後一定接括號 ()
Python 的資料科學入門

函式結構:位置引數

function-anatomy

位置引數(positional arguments)

  • 是函式的輸入,告訴函式怎麼做事
  • 順序很重要!
Python 的資料科學入門

函式結構:關鍵字引數

function-anatomy

關鍵字引數(keyword arguments)

  • 必須在位置引數之後
  • 先寫引數名稱(label),再接等號(=
  • 後面接引數值(Ransom
Python 的資料科學入門

常見函式錯誤

  • 引數之間少了逗號

  • 少了右括號

Python 的資料科學入門

一起來練習吧!

Python 的資料科學入門

Preparing Video For Download...