Python 入門指南 5.0

exercise2801.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 從 random 引入 randint
from random import randint
# 從 exercise2201 引入 higher
from exercise2202 import higher

# 命令列版本的猜數字遊戲
def guess_game():
    # 設定隨機答案
    answer = randint(1, 99)
    # 計算猜測次數
    count = 0
    # 猜對才結束遊戲
    while True:
        # 猜測次數遞增
        count += 1
        # 取得使用者輸入
        try:
            user_input = int(input("請輸入猜測數字:"))
        except ValueError:
            user_input = 0
            print("型態轉換錯誤")
        # 判斷使用者輸入是否合乎範圍
        if 1 <= user_input <= 99:
            # 印出猜對與否資訊
            if user_input == answer:
                print("恭喜猜對~~")
                break
            else:
                if higher(user_input, answer):
                    print("小一點!")
                else:
                    print("大一點!")
        else:
            print("輸入超出範圍")
    # 印出猜測次數
    print(f"一共猜了 {count} 次")

if __name__ == '__main__':
    guess_game()

# 檔名: exercise2801.py
# 說明:《Python入門指南》的練習
# 網站: http://kaiching.org
# 作者: 張凱慶
# 時間: 2023 年 11 月

回到練習題目
上一頁 exercise2710.py
回 Python 入門指南 5.0 首頁
下一頁 exercise2802.py
回 Python 教材首頁
回程式語言教材首頁