# 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) ``` ## 怎麼使用自己寫的函式呢?   例如我寫了計算閏年的函式,我把它存成function.py,把它和要引用它的程式放在同一個資料夾就行了! ## challenge!! 寫一個引用自己寫的函式的程式吧!
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up