Contents ...
udn網路城邦
python範例程式(一)
2025/10/18 11:50
瀏覽30
迴響0
推薦0
引用0
# ==============================

# 🧠 生活小幫手程式

# 提供服裝結帳、圓形計算、溫度轉換、複利計算等功能

# ==============================


# ------------------------------

# 📥 函式:讀取整數輸入

# 若輸入非整數,會提示重新輸入

# ------------------------------

def read_int(prompt):

    while True:

        try:

            return int(input(prompt))

        except ValueError:

            print("請輸入整數數字。")



# ------------------------------

# 📥 函式:讀取浮點數輸入

# 若輸入非數值,會提示重新輸入

# ------------------------------

def read_float(prompt):

    while True:

        try:

            return float(input(prompt))

        except ValueError:

            print("請輸入數值(可含小數)。")



# ------------------------------

# 👕 模組1:服裝結帳系統

# 計算上衣、褲子、背心的總金額

# ------------------------------

def checkout_clothes():

    print("\n服裝結帳:")

    上衣 = read_int("請輸入上衣數量? ")

    褲子 = read_int("請輸入褲子數量? ")

    背心 = read_int("請輸入背心數量? ")

    總金額 = 上衣 * 300 + 褲子 * 350 + 背心 * 400

    print(f訂購服裝的總金額為 {總金額} 元)



# ------------------------------

# ⚪ 模組2:圓形計算

# 根據半徑計算圓周長與面積

# ------------------------------

def circle_calc():

    print("\n圓形計算(圓周長與面積)")

    半徑 = read_float("請輸入半徑? ")

    PI = 3.14159

    圓周長 = 2 * PI * 半徑

    圓面積 = 半徑 * 半徑 * PI

    print(f圓周長為 {圓周長:.2f},圓面積為 {圓面積:.2f})



# ------------------------------

# 🌡️ 模組3:溫度換算

# 攝氏 → 華氏

# ------------------------------

def temp_convert():

    print("\n溫度換算(攝氏轉華氏)")

    # ⚠️ 修正格式化錯誤,原本是 {f:.2f}

    c = read_float("請輸入攝氏溫度: ")

    f = c * 9 / 5 + 32

    print(f"華氏溫度為 {f:.2f}")



# ------------------------------

# 💰 模組4:複利計算

# 計算本金在三年內的本利和

# ------------------------------

def compound_interest():

    print("\n複利計算(連續3年本利和)")

    money = read_int("請輸入本金? ")

    interest = read_float("請輸入年利率(%)? ")

    rate = 1 + interest / 100  # 年增長倍數

    y1 = money * (rate ** 1)

    y2 = money * (rate ** 2)

    y3 = money * (rate ** 3)

    print(f第一年本利和為 {y1:.2f})

    print(f第二年本利和為 {y2:.2f})

    print(f第三年本利和為 {y3:.2f})



# ------------------------------

# 🎛️ 主選單功能

# 讓使用者選擇想執行的模組

# ------------------------------

def main():

    while True:

        print("\n==== 生活小幫手 ====")

        print("1) 服裝結帳")

        print("2) 圓形計算")

        print("3) 溫度轉換 (攝氏→華氏)")

        print("4) 複利計算 (3年)")

        print("5) 離開")


        # ⚠️ 修正 input 的 .strip 錯誤 (應加上 ())

        choice = input("請選擇功能: ").strip()


        if choice == "1":

            checkout_clothes()

        elif choice == "2":

            circle_calc()

        elif choice == "3":

            temp_convert()

        elif choice == "4":

            compound_interest()

        elif choice == "5":

            print("感謝使用,掰掰~")

            break

        else:

            print("無效選項,請重新選擇。")



# ------------------------------

# 程式入口

# ------------------------------

if __name__ == "__main__":

    main()
全站分類:興趣嗜好 其他
上一則: python範例程式(二)
下一則: C語言範例程式-4

限會員,要發表迴響,請先登入