計算折扣
你正在為一個線上商店開發計算折扣後價格的功能。你希望能設定不同的折扣比例,並控制是否要在 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)