iT邦幫忙

0

【Python筆記】Python 函式基礎觀念

  • 分享至 

  • xImage
  •  

把重複動作包起來

生活情境:每天打招呼

def say_hello():
    print("你好,歡迎光臨!")

say_hello()

重點:
def:建立函式
say_hello:函式名稱
():放輸入資料的位置
呼叫函式:say_hello()

概念:
函式 = 幫你記住一段操作,以後直接叫它執行

帶入資料(參數 Parameter)

生活情境:不同客人的名字不同

def say_hello(name):
    print(f"你好,{name}!")

say_hello("小明")
say_hello("小美")

結果:

你好,小明!
你好,小美!

(f 是 f-string(formatted string literal,格式化字串)的意思)

重點:
name 是參數
呼叫時傳入實際資料
同一個函式可以處理不同情況

概念:
函式像機器,參數就是丟進去的材料

回傳結果(return)

生活情境:計算購物總價

def calculate_total(price, quantity):
    total = price * quantity
    return total

money = calculate_total(50, 3)

print(money)

結果:

150

重點:
return 把結果交出去
可以把結果存到變數
函式不一定要直接 print

概念:
print 是展示答案,return 是把答案交給別人使用

預設參數(Default Parameter)

生活情境:飲料甜度預設正常

def order_drink(name, sugar="正常"):
    print(f"{name},甜度:{sugar}")

order_drink("珍珠奶茶")
order_drink("綠茶", "半糖")

結果:

珍珠奶茶,甜度:正常
綠茶,甜度:半糖

重點:
可以設定預設值
使用者沒輸入時,自動使用預設值

概念:
就像點餐:「沒指定 → 使用店家的標準設定」

函式當作資料使用

生活情境:不同折扣方式

def discount_10(price):
    return price * 0.9

def discount_20(price):
    return price * 0.8
    
def checkout(price, discount_function):
    return discount_function(price)

print(checkout(1000, discount_10))
print(checkout(1000, discount_20))

結果:

900.0
800.0

重點:
函式可以當參數傳入
函式可以控制另一個函式
是 Python 很重要的特色

概念:
函式不只是工具,也可以像資料一樣被傳來傳去

函式核心整理

概念 用途 例子
def 建立函式 定義功能
參數 接收資料 姓名、價格
return 回傳結果 計算答案
預設參數 提供預設值 正常甜度
函式當參數 高階用法 不同折扣

簡單記憶

函式 = 輸入 → 處理 → 輸出
資料(參數) → 函式處理 → 結果(return)

學 Python 時,函式是從「寫程式」進入「設計程式」的重要分水嶺


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言