開始使用免費開始

計算折扣

你正在為一個線上商店開發計算折扣後價格的功能。你希望能設定不同的折扣比例,並控制是否要在 App 中將價格四捨五入,以讓顯示更乾淨。

在這個練習中,你會建立一個自訂函式,使用預設關鍵字引數來處理這些需求。

本練習屬於課程

Intermediate Python for Developers

檢視課程

練習說明

  • 定義 calculate_discount() 函式,並為 discount_percent(15)與 round_result(True)設定預設引數。
  • if 敘述裡將結果四捨五入到小數點後兩位。
  • 呼叫該函式,將 discount_percent 設為 25,並將 round_result 設為 False

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

original_price = 899.99

# Define the function with default arguments
def calculate_discount(price, ____=15, ____=True):
    discounted_price = price - (price * (discount_percent / 100))
    
    if round_result == True:
        # Round the result to two decimal places
        return ____(discounted_price, ____)
    else:
        return discounted_price

# Call the function with keyword arguments
final_price = calculate_discount(price=original_price, ____=___, ____=____)
print(final_price)
編輯並執行程式碼