คำนวณราคาส่วนลด
คุณกำลังสร้างฟีเจอร์สำหรับคำนวณราคาหลังหักส่วนลดในร้านค้าออนไลน์ โดยต้องการกำหนดจำนวนส่วนลดที่แตกต่างกันได้ และควบคุมว่าจะปัดเศษราคาให้ดูเรียบร้อยขึ้นในแอปหรือไม่
ในแบบฝึกหัดนี้ จะได้สร้างฟังก์ชันที่รองรับความต้องการเหล่านี้โดยใช้อาร์กิวเมนต์แบบ default และ keyword
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python ระดับกลางสำหรับนักพัฒนา
คำแนะนำการฝึกหัด
- นิยามฟังก์ชัน
calculate_discount()โดยกำหนด default arguments สำหรับdiscount_percent(15) และround_result(True) - ปัดผลลัพธ์ให้เหลือทศนิยม 2 ตำแหน่งภายใน
ifstatement - เรียกใช้ฟังก์ชันโดยกำหนด
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)