计算折扣
您正在为一家在线商店构建一个计算折后价的功能。您希望能够设置不同的折扣幅度,并控制价格是否四舍五入,以便在应用中显示更整洁。
在本练习中,您将创建一个自定义函数,通过使用默认参数和关键字参数来满足这些需求。
本练习是课程的一部分
Python 中级:面向开发者
练习说明
- 定义
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)