使用Python的运送计算器在我的代码中出现错误

时间:2019-03-10 19:17:43

标签: python

感谢大家的帮助。我知道了抱歉,我问了一个愚蠢的问题。似乎我在某些地方有太多空格,然后我的enter_more命令只是继续循环,但我再次感谢它。

print("Shipping Calculator \n")


enter_more="y"

while enter_more.lower()=="y":

   itemcost=float(input("Cost of items ordered:"))
   if itemcost < 0:
       print("You must enter a positive number. Please try again.")
       continue 

   if itemcost >75:

    Shipping_cost=0

   elif itemcost >50:

    Shipping_cost=9.95



   elif itemcost >30:

    Shipping_cost=7.95


   else: 

    Shipping_cost =5.95

   print("Shipping cost:",Shipping_cost)

   total_cost =round(Shipping_cost + itemcost,2)

   print ("Total cost:",round(Shipping_cost + itemcost,2))

   print()

   enter_more = input("Continuie? y/n:")

   if enter_more.lower()!= "y":

         break


print("Bye!")

1 个答案:

答案 0 :(得分:1)

您的代码应如下所示:

print("Shipping Calculator \n")
itemcost=float(input("Cost of items ordered:"))
if itemcost <30.00:
    Shipping_cost=5.95
elif itemcost >30.00 and itemcost <= 49.99:
    Shipping_cost=7.95
elif itemcost >50.00 and itemcost <=74.99:
    Shipping_cost=9.95
else: 
    print("Shipping cost is FREE") 

print("Shipping cost:" + str (itemcost) + Shipping_cost)

出现错误的原因是因为您的elif语句位于if内。


其他注意事项:

  • print()替换为\n也是一种更好的做法
  • format(Shipping_cost)可以替换为Shipping_cost
  • 如果要使用format(),则应将print("Shipping cost:" + str (itemcost) + Shipping_cost)更改为print("Shipping cost:{}{}".format(str(itemcost),Shipping_cost))