# 5.1 函式 ## 使用函式的好處 - 可重複使用 - 比較好讀懂 - 比較好除錯 ## 函式創建 ```python= def 函式名稱(參數): 程式碼 ``` ## 不帶輸入值的函式 ```python= def helloworld(): print(helloworld) helloworld() ``` ## 帶輸入值的函式 ```python= def bigger(num1,num2): if num1>num2: return(num1) elif num2>num1: return(num2) print(bigger(4,6)) ``` ‌ ## try it 請寫出一個能自動計算今年是不是閏年的函式! ‌ ### Ans: ``` def leapyear(): if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0): return True else: return False year=input('please input a Year\n') print(leapyear(year)) ``` ‌ # 區域變數 ‌ 全域變數:整個程式都可以用 ‌ 區域變數:函式內可以用 ```python= g = 5 def f(): #print(g) #global g g = 10 print(g) f() print(g) ``` # python標準函式庫 python內建了許多其他程式設計師作的函式庫,方便我們使用! 以random函式庫為例: ```python= import random as rd print(rd.randint(1,100)) ``` 匯入模組的不同方式: ```python= import random as rd import random from random import randint ``` 使用模組的方式和自己寫的函式相同! ```python= rd.randint(2,20200) ``` ## 怎麼使用自己寫的函式呢? ![img](https://gblobscdn.gitbook.com/assets%2F-MDZ74LOQcDUA3PMmePS%2F-MNrs88zqc0tjK7MXb_M%2F-MNs1-367qc12jC5ILO9%2F%E8%9E%A2%E5%B9%95%E6%93%B7%E5%8F%96%E7%95%AB%E9%9D%A2%202020-12-06%20203002.jpg?alt=media&token=ca383db8-dd85-49a3-867e-fb912582589f) ![img](https://gblobscdn.gitbook.com/assets%2F-MDZ74LOQcDUA3PMmePS%2F-MNrs88zqc0tjK7MXb_M%2F-MNs0YOk-XmKI5zNY-bP%2F%E8%9E%A2%E5%B9%95%E6%93%B7%E5%8F%96%E7%95%AB%E9%9D%A2%202020-12-06%20202805.jpg?alt=media&token=c841df33-a99b-426c-8d30-e3d29c58c006) 例如我寫了計算閏年的函式,我把它存成function.py,把它和要引用它的程式放在同一個資料夾就行了! ‌ ## challenge!! ‌ 寫一個引用自己寫的函式的程式吧!