---
# System prepended metadata

title: wk12_1123_函式模組_期末專題參考
tags: [python]

---

### wk12_1123_函式模組_期末專題參考

- 7.2 數值函式

- 7.3 字串函式

#### 【inclass practice】

###### {範例}
   
    學生分蘋果  \
    總和及排序  \
    檢查網址格式 \
    以字串排版函式列印成績單 \
    轉換日期格式 \
    大樂透中獎號碼 \


```python
#大樂透

import random 

list1 = random.sample(range(1,50),7)

special = list1.pop()
list1.sort()
print("中獎號碼:", end="")
for i in range(6):
    if i == 5: print(str(list1[i]))
    else: print(str(list1[i]), end=", ")
print("特別號:" +str(special))

```

    中獎號碼:25, 27, 35, 37, 39, 46
    特別號:26
    


```python
import random as secret

secret = "".join(r.sample("123456789", 4))
print(secret)

guess = "1234"

a = 0
b = 0

for i in range(4):
    if guess[i] == secret[i] :
        a = a+1
    elif guess[i] in secret[i] :
        b = b+1
```

    7512
    


```python
import random as r

def evaluate(guess) :
    a = 0
    b = 0
    
    for i in range(4):
        if guess[i] == secret[i] :
            a = a + 1
        elif guess[i] in secret[i] :
            b = b + 1
    return a, b

secret = "".join(r.sample("123456789", 4))
print(secret)

guess = input("guess, enterb4 number")

a, b = evaluate(guess)

print(f"{a}A{b}B")
```

    2364
    guess, enterb4 number1372
    1A0B
    

##### 期末專題參考 

{實戰#2} : 貪吃蛇 
- 貪吃蛇專案導讀


```python
! pip install pygame
```

    Collecting pygame
      Obtaining dependency information for pygame from https://files.pythonhosted.org/packages/82/61/93ae7afbd931a70510cfdf0a7bb0007540020b8d80bc1d8762ebdc46479b/pygame-2.5.2-cp311-cp311-win_amd64.whl.metadata
      Downloading pygame-2.5.2-cp311-cp311-win_amd64.whl.metadata (13 kB)
    Downloading pygame-2.5.2-cp311-cp311-win_amd64.whl (10.8 MB)
       ---------------------------------------- 0.0/10.8 MB ? eta -:--:--
       ---------------------------------------- 0.0/10.8 MB 640.0 kB/s eta 0:00:17
       ---------------------------------------- 0.1/10.8 MB 656.4 kB/s eta 0:00:17
       ---------------------------------------- 0.1/10.8 MB 930.9 kB/s eta 0:00:12
        --------------------------------------- 0.2/10.8 MB 1.1 MB/s eta 0:00:10
       - -------------------------------------- 0.3/10.8 MB 1.5 MB/s eta 0:00:08
       - -------------------------------------- 0.5/10.8 MB 1.8 MB/s eta 0:00:06
       -- ------------------------------------- 0.6/10.8 MB 1.9 MB/s eta 0:00:06
       --- ------------------------------------ 1.0/10.8 MB 2.8 MB/s eta 0:00:04
       --- ------------------------------------ 1.0/10.8 MB 2.8 MB/s eta 0:00:04
       ------- -------------------------------- 2.0/10.8 MB 4.6 MB/s eta 0:00:02
       ------- -------------------------------- 2.0/10.8 MB 4.6 MB/s eta 0:00:02
       --------- ------------------------------ 2.5/10.8 MB 4.5 MB/s eta 0:00:02
       ---------- ----------------------------- 2.9/10.8 MB 4.8 MB/s eta 0:00:02
       ----------- ---------------------------- 3.2/10.8 MB 5.1 MB/s eta 0:00:02
       -------------- ------------------------- 3.8/10.8 MB 5.6 MB/s eta 0:00:02
       ---------------- ----------------------- 4.3/10.8 MB 5.9 MB/s eta 0:00:02
       ----------------- ---------------------- 4.8/10.8 MB 6.1 MB/s eta 0:00:01
       ------------------- -------------------- 5.3/10.8 MB 6.4 MB/s eta 0:00:01
       --------------------- ------------------ 5.7/10.8 MB 6.5 MB/s eta 0:00:01
       ----------------------- ---------------- 6.3/10.8 MB 6.8 MB/s eta 0:00:01
       ------------------------ --------------- 6.6/10.8 MB 6.9 MB/s eta 0:00:01
       -------------------------- ------------- 7.2/10.8 MB 7.1 MB/s eta 0:00:01
       ---------------------------- ----------- 7.6/10.8 MB 7.1 MB/s eta 0:00:01
       ------------------------------ --------- 8.2/10.8 MB 7.3 MB/s eta 0:00:01
       -------------------------------- ------- 8.6/10.8 MB 7.3 MB/s eta 0:00:01
       --------------------------------- ------ 9.0/10.8 MB 7.5 MB/s eta 0:00:01
       --------------------------------- ------ 9.0/10.8 MB 7.5 MB/s eta 0:00:01
       ------------------------------------ --- 9.7/10.8 MB 7.6 MB/s eta 0:00:01
       ------------------------------------ --- 9.9/10.8 MB 7.4 MB/s eta 0:00:01
       ------------------------------------ --- 9.9/10.8 MB 7.4 MB/s eta 0:00:01
       ---------------------------------------- 10.8/10.8 MB 8.8 MB/s eta 0:00:00
    Installing collected packages: pygame
    Successfully installed pygame-2.5.2
    


```python
"""
Snake Eater
Made with PyGame
"""

import pygame, sys, time, random


# Difficulty settings
# Easy      ->  10
# Medium    ->  25
# Hard      ->  40
# Harder    ->  60
# Impossible->  120
difficulty = 10

# Window size
frame_size_x = 720
frame_size_y = 480

# Checks for errors encountered
check_errors = pygame.init()
# pygame.init() example output -> (6, 0)
# second number in tuple gives number of errors
if check_errors[1] > 0:
    print(f'[!] Had {check_errors[1]} errors when initialising game, exiting...')
    sys.exit(-1)
else:
    print('[+] Game successfully initialised')


# Initialise game window
pygame.display.set_caption('Snake Eater')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))


# Colors (R, G, B)
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)


# FPS (frames per second) controller
fps_controller = pygame.time.Clock()


# Game variables
snake_pos = [100, 50]
snake_body = [[100, 50], [100-10, 50], [100-(2*10), 50]]

food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True

direction = 'RIGHT'
change_to = direction

score = 0


# Game Over
def game_over():
    my_font = pygame.font.SysFont('times new roman', 90)
    game_over_surface = my_font.render('YOU DIED', True, red)
    game_over_rect = game_over_surface.get_rect()
    game_over_rect.midtop = (frame_size_x/2, frame_size_y/4)
    game_window.fill(black)
    game_window.blit(game_over_surface, game_over_rect)
    show_score(0, red, 'times', 20)
    pygame.display.flip()
    time.sleep(3)
    pygame.quit()
    sys.exit()


# Score
def show_score(choice, color, font, size):
    score_font = pygame.font.SysFont(font, size)
    score_surface = score_font.render('Score : ' + str(score), True, color)
    score_rect = score_surface.get_rect()
    if choice == 1:
        score_rect.midtop = (frame_size_x/10, 15)
    else:
        score_rect.midtop = (frame_size_x/2, frame_size_y/1.25)
    game_window.blit(score_surface, score_rect)
    # pygame.display.flip()


# Main logic
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # Whenever a key is pressed down
        elif event.type == pygame.KEYDOWN:
            # W -> Up; S -> Down; A -> Left; D -> Right
            if event.key == pygame.K_UP or event.key == ord('w'):
                change_to = 'UP'
            if event.key == pygame.K_DOWN or event.key == ord('s'):
                change_to = 'DOWN'
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                change_to = 'LEFT'
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                change_to = 'RIGHT'
            # Esc -> Create event to quit the game
            if event.key == pygame.K_ESCAPE:
                pygame.event.post(pygame.event.Event(pygame.QUIT))

    # Making sure the snake cannot move in the opposite direction instantaneously
    if change_to == 'UP' and direction != 'DOWN':
        direction = 'UP'
    if change_to == 'DOWN' and direction != 'UP':
        direction = 'DOWN'
    if change_to == 'LEFT' and direction != 'RIGHT':
        direction = 'LEFT'
    if change_to == 'RIGHT' and direction != 'LEFT':
        direction = 'RIGHT'

    # Moving the snake
    if direction == 'UP':
        snake_pos[1] -= 10
    if direction == 'DOWN':
        snake_pos[1] += 10
    if direction == 'LEFT':
        snake_pos[0] -= 10
    if direction == 'RIGHT':
        snake_pos[0] += 10

    # Snake body growing mechanism
    snake_body.insert(0, list(snake_pos))
    if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
        score += 1
        food_spawn = False
    else:
        snake_body.pop()

    # Spawning food on the screen
    if not food_spawn:
        food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
    food_spawn = True

    # GFX
    game_window.fill(black)
    for pos in snake_body:
        # Snake body
        # .draw.rect(play_surface, color, xy-coordinate)
        # xy-coordinate -> .Rect(x, y, size_x, size_y)
        pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))

    # Snake food
    pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

    # Game Over conditions
    # Getting out of bounds
    if snake_pos[0] < 0 or snake_pos[0] > frame_size_x-10:
        game_over()
    if snake_pos[1] < 0 or snake_pos[1] > frame_size_y-10:
        game_over()
    # Touching the snake body
    for block in snake_body[1:]:
        if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
            game_over()

    show_score(1, white, 'consolas', 20)
    # Refresh game screen
    pygame.display.update()
    # Refresh rate
    fps_controller.tick(difficulty)
```

    pygame 2.5.2 (SDL 2.28.3, Python 3.11.4)
    Hello from the pygame community. https://www.pygame.org/contribute.html
    [+] Game successfully initialised
    


    An exception has occurred, use %tb to see the full traceback.
    

    SystemExit
    


    C:\Users\cjc11\anaconda3\Lib\site-packages\IPython\core\interactiveshell.py:3513: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
      warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
    


```python
import pygame, sys, time, random

difficulty = 10

frame_size_x = 720
frame_size_y = 480

pygame.display.set_caption('Snake !')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))

black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)

fps_controller = pygame.time.Clock()

snake_pos = [100, 50]
snake_body = [[100, 50], [100-10, 50], [100-(2*10), 50]]

food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
food_spawn = True

direction = 'RIGHT'
change_to = direction

score = 0

def game_over():
    my_font = pygame.font.SysFont('times new roman', 90)
    game_over_surface = my_font.render('YOU DIED', True, red)
    game_over_rect = game_over_surface.get_rect()
    game_over_rect.midtop = (frame_size_x/2, frame_size_y/4)
    game_window.fill(black)
    game_window.blit(game_over_surface, game_over_rect)
    show_score(0, red, 'times', 20)
    pygame.display.flip()
    time.sleep(3)
    pygame.quit()
    sys.exit()

def show_score(choice, color, font, size):
    score_font = pygame.font.SysFont(font, size)
    score_surface = score_font.render('Score : ' + str(score), True, color)
    score_rect = score_surface.get_rect()
    if choice == 1:
        score_rect.midtop = (frame_size_x/10, 15)
    else:
        score_rect.midtop = (frame_size_x/2, frame_size_y/1.25)
    game_window.blit(score_surface, score_rect)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP or event.key == ord('w'):
                change_to = 'UP'
            if event.key == pygame.K_DOWN or event.key == ord('s'):
                change_to = 'DOWN'
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                change_to = 'LEFT'
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                change_to = 'RIGHT'
            if event.key == pygame.K_ESCAPE:
                pygame.event.post(pygame.event.Event(pygame.QUIT))

    if change_to == 'UP' and direction != 'DOWN':
        direction = 'UP'
    if change_to == 'DOWN' and direction != 'UP':
        direction = 'DOWN'
    if change_to == 'LEFT' and direction != 'RIGHT':
        direction = 'LEFT'
    if change_to == 'RIGHT' and direction != 'LEFT':
        direction = 'RIGHT'


    if direction == 'UP':
        snake_pos[1] -= 10
    if direction == 'DOWN':
        snake_pos[1] += 10
    if direction == 'LEFT':
        snake_pos[0] -= 10
    if direction == 'RIGHT':
        snake_pos[0] += 10


    snake_body.insert(0, list(snake_pos))
    if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
        score += 1
        food_spawn = False
    else:
        snake_body.pop()

    if not food_spawn:
        food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10]
    food_spawn = True

    game_window.fill(black)
    for pos in snake_body:
      
        pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))

    pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

    if snake_pos[0] < 0 or snake_pos[0] > frame_size_x-10:
        game_over()
    if snake_pos[1] < 0 or snake_pos[1] > frame_size_y-10:
        game_over()
    for block in snake_body[1:]:
        if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
            game_over()

    show_score(1, white, 'consolas', 20)
            
    pygame.display.update()
    fps_controller.tick(difficulty)
```

#### 【afterclass practice】

- 尋找期末專題主題
- {範例}
 
      學生分蘋果  \
      總和及排序  \
      檢查網址格式 \
      以字串排版函式列印成績單 \
      轉換日期格式 \
- {綜合演練}

      實作3
      實作4


```python
#學生分蘋果

person = int(input("請輸入學生人數:"))
apple = int(input("請輸入蘋果總数:"))
ret = divmod(apple, person)
print("每個學生可分得蘋果"+str(ret[0])+"個")
print("蘋果剩餘" + str(ret[1])+" 個")
```

    請輸入學生人數:56
    請輸入蘋果總数:700
    每個學生可分得蘋果12個
    蘋果剩餘28 個
    


```python
#總和及排序

innum = 0
list1 = []
while(innum != -1):
    innum = int(input("請輸入電費(-1:結束):"))
    list1.append(innum)
list1.pop()
print("共輸入 %d 個數" % len(list1))
print("最多電費為:%d" % max(list1))
print("最少電费為:%d" % min(list1))
print("電費總和為:%d" % sum(list1))
print("電费由大到小排序為:{}".format(sorted(list1,reverse = True)))
```

    請輸入電費(-1:結束):2500
    請輸入電費(-1:結束):2000
    請輸入電費(-1:結束):1750
    請輸入電費(-1:結束):-1
    共輸入 3 個數
    最多電費為:2500
    最少電费為:1750
    電費總和為:6250
    電费由大到小排序為:[2500, 2000, 1750]
    


```python
#檢查網址格式

web=input("請輸入網址:")
if web.startswith("http://") or web.startswith("https://"):
    print("輸入的網址格式正!")
else:
    print("輸入的網址格式錯誤!")
```

    請輸入網址:http
    輸入的網址格式錯誤!
    


```python
#以字串排版函式列印成績單 

listname =["林大明","陳阿中","張小英"]
listchinese = [100, 74, 82]
listmath = [87, 88, 65]
listenglish = [79, 100, 8]
print("姓名     座號  國文   数学  英文")
for i in range(0,3):
    print(listname[i].ljust(5), str(i+1).rjust(3),
    str(listchinese[i]).rjust(5), str(listmath[i]).
    rjust(5), str(listenglish[i]).rjust(5))
```

    姓名     座號  國文   数学  英文
    林大明     1   100    87    79
    陳阿中     2    74    88   100
    張小英     3    82    65     8
    


```python
#轉換日期格式

datel ="2017-8-23"
datel = "西元 " + datel
datel = datel.replace("-", " 年 ", 1)
datel = datel.replace("-", " 月 ", 1)
datel += " 日"
print(datel)
```

    西元 2017 年 8 月 23 日
    

{綜合演練}


```python
#實作3

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)
```

    現在時刻：下午 10 點 20 分 29 秒
    


```python
#實作4

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
```

    請輸入換幣金額：300
    50元 * 6個
    

#### 【selfpractice】


```python
import random

def generate_lottery_numbers():
    lottery_numbers = random.sample(range(1, 50), 7)
    return sorted(lottery_numbers[:6]), lottery_numbers[6]

def simulate_lottery():
    # 產生開獎號碼
    winning_numbers, winning_special = generate_lottery_numbers()
    print("本期大樂透開獎中...")
    print("本期中獎號碼為：", winning_numbers, "特別號是：", winning_special)
    

# 模擬開獎
simulate_lottery()
```

    本期大樂透開獎中...
    本期中獎號碼為： [15, 17, 20, 25, 30, 42] 特別號是： 13
    


```python
import random

def generate_lottery_numbers():
    lottery_numbers = random.sample(range(1, 50), 7)
    return sorted(lottery_numbers[:6]), lottery_numbers[6]

def check_numbers(player_numbers, player_special, winning_numbers, winning_special):
    correct_numbers = len(set(player_numbers).intersection(set(winning_numbers)))
    correct_special = 1 if player_special == winning_special else 0
    return correct_numbers, correct_special

def simulate_lottery():
    winning_numbers, winning_special = generate_lottery_numbers()
    print("本期大樂透開獎中...")
    print("本期中獎號碼為：", winning_numbers, "特別號是：", winning_special)
    
    # 選號
    player_numbers = []
    for i in range(6):
        while True:
            try:
                number = int(input(f"請輸入你的第 {i+1} 個數字 (1-49)："))
                if number < 1 or number > 49:
                    raise ValueError
                if number in player_numbers:
                    raise ValueError("數字重複選擇")
                player_numbers.append(number)
                break
            except ValueError:
                print("請輸入有效的數字並避免重複選擇")
    
    while True:
        try:
            special = int(input("請輸入你的特別號碼 (1-49)："))
            if special < 1 or special > 49:
                raise ValueError
            break
        except ValueError:
            print("請輸入有效的特別號碼")

    # 檢查中獎
    correct_numbers, correct_special = check_numbers(player_numbers, special, winning_numbers, winning_special)
    
    # 輸出結果
    print("\n你的選號為：", sorted(player_numbers), "特別號是：", special)
    print("本期中獎號碼為：", winning_numbers, "特別號是：", winning_special)
    print("\n你猜對了", correct_numbers, "個數字", "和特別號" if correct_special else "沒有特別號")

simulate_lottery()
```

    本期大樂透開獎中...
    本期中獎號碼為： [6, 8, 20, 33, 46, 49] 特別號是： 25
    請輸入你的第 1 個數字 (1-49)：5
    請輸入你的第 2 個數字 (1-49)：8
    請輸入你的第 3 個數字 (1-49)：19
    請輸入你的第 4 個數字 (1-49)：20
    請輸入你的第 5 個數字 (1-49)：45
    請輸入你的第 6 個數字 (1-49)：48
    請輸入你的特別號碼 (1-49)：25
    
    你的選號為： [5, 8, 19, 20, 45, 48] 特別號是： 25
    本期中獎號碼為： [6, 8, 20, 33, 46, 49] 特別號是： 25
    
    你猜對了 2 個數字 和特別號
    


```python
import random

def generate_lottery_numbers():
    lottery_numbers = random.sample(range(1, 50), 7)
    return sorted(lottery_numbers[:6]), lottery_numbers[6]

def check_numbers(player_numbers, player_special, winning_numbers, winning_special):
    correct_numbers = len(set(player_numbers).intersection(set(winning_numbers)))
    correct_special = 1 if player_special == winning_special else 0
    return correct_numbers, correct_special

def simulate_lottery():
    winning_numbers, winning_special = generate_lottery_numbers()
    
    player_numbers = []
    for i in range(6):
        while True:
            try:
                number = int(input(f"請輸入你的第 {i+1} 個數字 (1-49)："))
                if number < 1 or number > 49:
                    raise ValueError
                if number in player_numbers:
                    raise ValueError("數字重複選擇")
                player_numbers.append(number)
                break
            except ValueError:
                print("請輸入有效的數字並避免重複選擇")
    
    while True:
        try:
            special = int(input("請輸入你的特別號碼 (1-49)："))
            if special < 1 or special > 49:
                raise ValueError
            break
        except ValueError:
            print("請輸入有效的特別號碼")
    
    # 顯示開獎號碼
    print("\n本期大樂透開獎中...")
    input("按下 Enter 顯示開獎號碼...")
    print("本期中獎號碼為：", winning_numbers, "特別號是：", winning_special)
    
    # 檢查中獎
    correct_numbers, correct_special = check_numbers(player_numbers, special, winning_numbers, winning_special)
    
    # 輸出結果
    print("\n你的選號為：", sorted(player_numbers), "特別號是：", special)
    print("\n你猜對了", correct_numbers, "個數字和", "特別號" if correct_special else "沒有特別號")

simulate_lottery()
```

    請輸入你的第 1 個數字 (1-49)：7
    請輸入你的第 2 個數字 (1-49)：15
    請輸入你的第 3 個數字 (1-49)：26
    請輸入你的第 4 個數字 (1-49)：28
    請輸入你的第 5 個數字 (1-49)：35
    請輸入你的第 6 個數字 (1-49)：41
    請輸入你的特別號碼 (1-49)：42
    
    本期大樂透開獎中...
    按下 Enter 顯示開獎號碼...
    本期中獎號碼為： [12, 16, 22, 23, 29, 34] 特別號是： 44
    
    你的選號為： [7, 15, 26, 28, 35, 41] 特別號是： 42
    
    你猜對了 0 個數字和 沒有特別號
    
