5 2 def def function Nameparameters statements returnreturn

  • Slides: 14
Download presentation

5 -2 定義函式 我們可以使用def關鍵字定義函式,其語法如下: def function. Name([parameters]): statements [return|return value] [statements] 例如: def Cto.

5 -2 定義函式 我們可以使用def關鍵字定義函式,其語法如下: def function. Name([parameters]): statements [return|return value] [statements] 例如: def Cto. F 1(degree. C): degree. F = degree. C * 1. 8 + 32 print("攝氏", degree. C, "度可以轉換成華氏", degree. F, "度") 例如: def Cto. F 2(degree. C): degree. F = degree. C * 1. 8 + 32 return degree. F 一步到位 ! Python

5 -3 呼叫函式 函式必須加以呼叫才會執行,其語法如下: function. Name([parameters]) 例如: def Cto. F 1(degree. C): degree. F

5 -3 呼叫函式 函式必須加以呼叫才會執行,其語法如下: function. Name([parameters]) 例如: def Cto. F 1(degree. C): degree. F = degree. C * 1. 8 + 32 print("攝氏", degree. C, "度可以轉換成華氏", degree. F, "度") temperature. C = eval(input("請輸入攝氏溫度:")) Cto. F 1(temperature. C) 一步到位 ! Python

5 -4 函式的參數(2/4) 5 -4 -2 關鍵字引數 Python預設採取位置引數 (position argument),但有些參數順序 實在不好記,此時可以使用關鍵字引數 (keyword argument) 來做

5 -4 函式的參數(2/4) 5 -4 -2 關鍵字引數 Python預設採取位置引數 (position argument),但有些參數順序 實在不好記,此時可以使用關鍵字引數 (keyword argument) 來做 區分,也就是在呼叫函式時指定引數所對應的參數名稱,下面是 一個例子。 def trapezoid. Area(top, bottom, height): result = (top + bottom) * height / 2 print("這個梯形面積為", result) trapezoid. Area(10, 20, 5) trapezoid. Area(10, height = 5, bottom = 20) trapezoid. Area(height = 5, bottom = 20, top = 10) 一步到位 ! Python

5 -4 函式的參數(4/4) 5 -4 -4 任意引數串列 Python支援任意引數串列 (arbitrary argument list) 的功能,也就 是函式接受不限定個數的參數,下面是一個例子。 def add(*numbers):

5 -4 函式的參數(4/4) 5 -4 -4 任意引數串列 Python支援任意引數串列 (arbitrary argument list) 的功能,也就 是函式接受不限定個數的參數,下面是一個例子。 def add(*numbers): total = 0 for i in numbers: total = total + i return total print(add(1)) print(add(1, 2, 3)) print(add(1, 2, 3, 4, 5)) 一步到位 ! Python

5 -9 日期時間函式(1/2) 5 -9 -1 time模組有一些時間屬性和時間函式,常用的如下,在使用time模 組之前,必須使用import指令進行匯入: >>> import time • time. daylight

5 -9 日期時間函式(1/2) 5 -9 -1 time模組有一些時間屬性和時間函式,常用的如下,在使用time模 組之前,必須使用import指令進行匯入: >>> import time • time. daylight • timezone • time. altzone • time() • time. clock() • time. gmtime([secs]) • time. ctime([secs]) • time. mktime(t) • time. sleep(secs) • time. strftime(format[, t]) • time. strptime(string[, format]) • time. localtime([secs]) • time. asctime([t]) 一步到位 ! Python

5 -9 日期時間函式(2/2) 5 -9 -2 calendar模組有一些日曆函式,常用的如下,在使用calendar模組 之前,必須使用import指令進行匯入: >>> import calendar • calendar. firstweekday()

5 -9 日期時間函式(2/2) 5 -9 -2 calendar模組有一些日曆函式,常用的如下,在使用calendar模組 之前,必須使用import指令進行匯入: >>> import calendar • calendar. firstweekday() • calendar. setfirstweekday(weekday) • calendar. isleap(year) • calendar. weekday(year, month, day) • calendar. monthrange(year, month) • calendar(year) • calendar. month(year, month) 一步到位 ! Python