2025年9月30日 星期二

[水井USR創新教材]Python一下用魚菜共生模擬小例子來說明函式的基本概念

 


以下是由ChatGPT協助生成:

範例一:全域變數與區域變數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 全域變數
global_factor = 10

def multiply_by_global(x):
    # 函式內可以讀取全域變數
    result = x * global_factor
    print(f"在函式中,x={x},global_factor={global_factor},result={result}")

def use_local_variable():
    # 區域變數:只在這個函式裡有效
    local_factor = 5
    print(f"local_factor 只在這個函式內有效:{local_factor}")

multiply_by_global(3)
use_local_variable()

# print(local_factor)  # ❌ 會出錯,因為 local_factor 是區域變數

執行結果:
在函式中,x=3,global_factor=10,result=30
local_factor 只在這個函式內有效:5

📌 重點:

  • global_factor 是全域變數,整個程式都能用。

  • local_factor 是區域變數,函式外無法存取。


範例二:函式的定義、呼叫與回傳值
1
2
3
4
5
6
7
def square(x):
    """回傳 x 的平方"""
    return x * x

# 呼叫函式
result = square(5)
print(f"5 的平方是 {result}")

執行結果:
5 的平方是 25

📌 重點:

  • def 是定義函式的關鍵字。

  • 使用 return 回傳結果;呼叫函式時可接收該值


範例三:函式中「有預設值」的參數,一定要放在後面

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# ❌ 錯誤寫法:有預設值的參數在前
# def greeting(message="Hello", name):
#     print(f"{message}, {name}")

# ✅ 正確寫法:無預設值的在前,有預設值的在後
def greeting(name, message="Hello"):
    print(f"{message}, {name}")

greeting("水井村")              # 使用預設值
greeting("歡迎光臨", "水井村")      # 覆寫預設值

執行結果:
Hello, 水井村
水井村, 歡迎光臨

📌 重點:

Python 函式定義時,預設值參數必須放在沒有預設值參數之後。

範例四:多個回傳值

1
2
3
4
5
6
7
def get_min_max(numbers):
    """回傳最小值與最大值(tuple)"""
    return min(numbers), max(numbers)

nums = [5, 2, 9, 1, 7]
minimum, maximum = get_min_max(nums)
print(f"最小值: {minimum}, 最大值: {maximum}")

執行結果:
最小值: 1, 最大值: 9

📌 重點:

  • 函式可以回傳多個值(實際是回傳 tuple)。

  • 可以同時接收多個變數來解包。


範例五:位置引數與關鍵字引數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def describe_pond(location, area, fish_type="吳郭魚"):
    print(f"地點:{location},面積:{area} m²,魚種:{fish_type}")

# 位置引數(依順序)
describe_pond("水井村", 100)
def describe_pond(location, area, fish_type="吳郭魚"):
    print(f"地點:{location},面積:{area} m²,魚種:{fish_type}")

# 位置引數(依順序)
describe_pond("水井村", 100)

# 關鍵字引數(不用依順序)
describe_pond(area=200, location="口湖鄉", fish_type="文蛤")

# 混用:位置引數要放前面
describe_pond("口湖鄉水井村", area=50)

執行結果:
地點:水井村,面積:100 m²,魚種:吳郭魚
地點:口湖鄉,面積:200 m²,魚種:文蛤
地點:口湖鄉水井村,面積:50 m²,魚種:吳郭魚

📌 重點:

  • 位置引數:按照順序傳入。

  • 關鍵字引數:用「參數名=值」指定。

  • 混用時,位置引數必須在關鍵字引數之前。

範例六:與「魚菜共生模擬」結合的小例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import random

# 全域變數
global_area = 3.3058

def single_month_simulation(month, area=global_area, base_emission=1.5):
    """模擬單月減碳量,示範回傳值與預設值參數"""
    seasonal_factor = 1.2 if 6 <= (month % 12 or 12) <= 8 else 1.0
    monthly_emission = base_emission / 12
    carbon = monthly_emission * area * seasonal_factor + random.uniform(-1, 1)
    return round(carbon, 2)  # 回傳單月減碳量

# 位置引數
print(single_month_simulation(1))

# 關鍵字引數
print(single_month_simulation(month=7, area=5))

# 使用全域變數(不傳 area)
print(single_month_simulation(3))

執行結果:
0.89
1.2
0.0

📌 重點:

  • 使用了預設值參數 + 關鍵字引數。

  • 示範全域變數作為預設參數。

  • 回傳單一計算值並列印。


沒有留言:

張貼留言