## ch07_函式與模組
```
7.1 自訂函式
1.自訂函式
2.參數預設值
3.變數有效範圍
7.2 數值函式
1.數值函式整理
2.指數、商數、餘數及四捨六入
3.最大值、最小值、總和及排序
7.3 字串函式
1.字串函式整理
2.連接及分割字串
3.檢查起始或結束字串
4.字串排版相關函式
5.搜尋即取代字串
7.4 亂數模組
1.import 模組
2.亂數模組函式整理
3.產生整數或浮點數的亂數函式
4.隨機取得字元或串列元素
7.5 時間模組
1.時間模組函式整理
2.取得時間訊息函式
3.執行程式相關時間函式
```
【inclass practice】
{綜合演練}
實作3:
以十二小時(上午、下午)顯示現在時刻。
實作4:
小華媽媽上菜市場買菜,找錢時她希望在1元、5元、10元、50元硬幣中找回最少的硬幣。小華就利用自訂函式幫媽媽寫了一個程式。
```python
import time as t
time1 = t.localtime()
show = "現在時刻:"
if time1.tm_hour < 12:
show += "上午 "
hour = time1.tm_hour
else:
show += "下午 "
hour = time1.tm_hour - 12
show += str(hour) + " 點 " + str(time1.tm_min) + " 分 "
show += str(time1.tm_sec) + " 秒"
print(show)
```
現在時刻:上午 1 點 29 分 12 秒
```python
def change(n,coin): # 換硬幣
m = n // coin # 硬幣數
return m
money=[50,10,5,1]
n=int(input("請輸入換幣金額:"))
while (n>0):
for i in range(len(money)):
coin = money[i]
if (n >= coin):
m = change(n,coin) # 換硬幣
print("{}元 * {}個" .format(coin,m))
n= n % coin
```
請輸入換幣金額:1200
50元 * 24個
#### {範例}
攝氏溫度轉華氏溫度 \
學生分蘋果 \
總和及排序 \
檢查網址格式 \
以字串排版函式列印成績單 \
轉換日期格式 \
擲骰子遊戲 \
大樂透中獎號碼 \
列印時間函式所有資訊 \
計算執行一百萬次整數運算的時間 \
{補充練習}
1A2B
函式1 : 數字相同+位置相同
函式2 : 數字相同 + 位置不同
```python
import time
print("hello")
time.sleep(1)
print("ww")
```
hello
ww
```python
import time as t
print("hello")
t.sleep(1)
print("Leo")
```
hello
Leo
```python
from time import sleep, perf_counter
print("hello")
print("Leo")
```
hello
Leo
```python
for i in range(11):
print(i)
sleep(1)
```
0
1
2
3
4
5
6
7
8
9
10
```python
startTime = perf_counter()
for i in range(3):
print(i)
sleep(0.9962)
endTime = perf_counter()
print(f"總費時:{endTime - startTime}秒")
```
0
1
2
總費時:3.018002499999966秒
```python
t.localtime()
```
time.struct_time(tm_year=2023, tm_mon=11, tm_mday=16, tm_hour=14, tm_min=6, tm_sec=14, tm_wday=3, tm_yday=320, tm_isdst=0)
```python
t.ctime()
```
'Thu Nov 16 14:06:24 2023'
```python
import random as r
while True:
inkey = input("按任意鍵 然後enter,擲骰子;若要結束遊戲,請直接enter:")
#random.randint(min,max) 產生隨機亂數
if len(inkey) :
print(r.randint(1,6))
else :
print("game over")
break
```
按任意鍵 然後enter,擲骰子;若要結束遊戲,請直接enter:5
1
按任意鍵 然後enter,擲骰子;若要結束遊戲,請直接enter:55
5
按任意鍵 然後enter,擲骰子;若要結束遊戲,請直接enter:45
2
按任意鍵 然後enter,擲骰子;若要結束遊戲,請直接enter:
game over
```python
#額外練習
players = ['curry', 'jordan', 'james']
for player in players:
print(f"{player.title()}, it was a great game.")
print(f"我迫不及待想看下一場比賽 {player.title()}")
```
Curry, it was a great game.
我迫不及待想看下一場比賽 Curry
Jordan, it was a great game.
我迫不及待想看下一場比賽 Jordan
James, it was a great game.
我迫不及待想看下一場比賽 James
### 【afterclass practice】
```
教學影音:
新手入門 #07 Function (函式)
新手入門 #09 Module (模組)
期末分組名單
```