[英]If-Elif-Else Python (Discount Scenario)
我正在研究該程序,該程序根據客戶購買的數量提供折扣。
方向如下:某些在線商店根據購買的總金額提供折扣:
If the purchase total is over $50, a 5% discount is applied
If the purchase total is over $100, a 10% discount is applied
If the purchase total is over $500, a 15% discount is applied
應用折扣后,使用if-elif-else鏈計算購買金額。 對於您的演示,請購買499.99美元。
到目前為止,這是我創建的,但是它似乎無法正常運行,我想知道如何才能使我的代碼變得更好,以及是否可以正確使用if-elif-else代碼。 謝謝大家。
if total_cost>=10:
if give_shopper_5percent_discount():
print"You have won a discount"
total_cost -= discount
candidate_prime =True
elif total_cost>100:
if give_shopper_10percent_discount():
print"You have won a discount"
total_cost -= discount
candidate_prime =True
else total_cost>=500:
if give_shopper_15percent_discount():
print"You have won a discount"
total_cost -= discount
candidate_prime =True
根據您的描述,第一個total_cost
限制是錯誤的。 而且您不應該在total_cost >= 500
之前使用else
嘗試這個:
total_cost = int(input('Please enter a total_cost:'))
if total_cost>=500:
print"You have won a discount by 15 percent"
total_cost *= 0.85
elif total_cost>100:
print"You have won a discount by 10 percent"
total_cost *= 0.9
elif total_cost>=50:
print"You have won a discount by 5 percent"
total_cost *= 0.95
else:
print 'you total cost is not in the range of discount!'
print 'Now the total cost is ', total_cost
您必須先檢查最大的折扣,否則您將按預期給予更多折扣;-)
if total_cost>=500:
...
elif total_cost>=100:
...
elif total_cost>=10:
...
else:
pass
您的縮進已經過時了。 在python中很重要。 (嘗試這個?)
if give_shopper_5percent_discount():
print"You have won a discount"
total_cost -= discount
candidate_prime =True
elif total_cost>100:
if give_shopper_10percent_discount():
print"You have won a discount"
total_cost -= discount
candidate_prime =True
else total_cost>=500:
if give_shopper_15percent_discount():
print"You have won a discount"
total_cost -= discount
candidate_prime =True
對於折扣,也可以嘗試乘而不是減。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.