If-Elif-Else Python(折扣情景)

时间:2014-09-25 03:08:12

标签: python if-statement

我正在制定此计划,根据客户购买的数量提供折扣。

方向如下:  某些在线商店根据购买总额给出折扣:

        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

3 个答案:

答案 0 :(得分:1)

根据您的描述,第一个total_cost限制是错误的。你不应该在total_cost >= 500

之前使用别的

试试这个:

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

答案 1 :(得分:1)

您必须先检查最大折扣,否则您可以按预期给予更多折扣; - )

if total_cost>=500:
  ...
elif total_cost>=100:
  ...
elif total_cost>=10:
  ...
else: 
  pass

答案 2 :(得分:0)

你的缩进是不合时宜的。在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

也适用于折扣尝试倍增而不是减去。