我正试图使用IF语句在python中制作一个Shipping计算器。应用程序应计算订单的总成本,包括运费。我陷入了python根本无法运行我的代码的困境。我有一种接近的感觉,但我不知道我输入的内容出了什么问题,因为python不会返回任何错误。请有人把我带向正确的方向。
说明:
创建一个程序,用于计算订单的总成本(包括运费(。
当你的程序运行时,它应该。。。
- 打印程序的名称"运费计算器">
- 提示用户键入订购项目的成本
- 如果用户输入的数字小于零,则显示一条错误消息,并让用户有机会再次输入该数字。(注意:如果你知道循环/迭代,可以在这里使用,但如果不知道,只需要用if语句进行简单的一次性检查就可以了。(例如:如果成本小于零,则打印一条错误消息,然后再次请求输入一次
使用下表计算运输成本:
物品成本 | |
---|---|
<30 | 5.95 |
30.00-49.99 | 7.95 |
50.00-74.99 | |
>75.00 | 免费 |
首先,我将把代码放在这里,然后解释我所做的所有更改(您最初的尝试非常接近,只是做了一些调整(:
#Assignment shipping calculator
#Author: Name
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping(subtotal)
calc_total(subtotal,shipping)
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
while subtotal <= 0:
print("You must enter a positive number. Please try again.")
subtotal = float(input("Cost of Items Ordered: $"))
return subtotal
def calc_shipping(subtotal):
if subtotal >= 1 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
return shipping
def calc_total(subtotal,shipping):
total = subtotal + shipping
print("Total Cost: $" + str(round(total,2)))
print("Thank you for using our shipping calculator!")
main()
正如@Devang Sanghani所提到的,您应该在函数之外调用
main()
,以便它运行对于
calc_subtotal()
函数,使用while循环不断接受用户输入,直到给出有效的数字。请确保将return subtotal
移到此循环之外,以便它只在该数字有效时返回。在
calc_shipping()
函数中,确保将subtotal
作为参数,因为您在函数中使用它。确保您也返回shipping
。类似地,在
calc_total()
函数中,将subtotal
和shipping
都作为参数,因为它们在函数中使用。鉴于这些变化,请相应地更新您的
main()
函数。
我希望这些改变有意义!如果您需要任何进一步的帮助或澄清,请告诉我:(
除了上面的答案之外,还考虑价格可以是几美分的情况,所以这一行应该改变:
if subtotal >= 0 and subtotal <= 29.99: # changed from 1 to 0
所以似乎有两个错误:
- 您忘记调用主函数
- 您缩进了
calc_subtotal()
中的return语句,因此它只在subtotal <= 0
正确的代码可能是:
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping()
total = calc_total()
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
if subtotal <= 0:
print("You must enter a positive number. Please try again.")
calc_subtotal() # Re asking for the input in case of invalid input
else:
return subtotal # returning subtotal in case of valid input
def calc_shipping():
subtotal = calc_subtotal()
shipping = calc_shipping
if subtotal >= 0 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
def calc_total():
total = calc_subtotal() + calc_shipping()
print("Total Cost: ",total)
print("Thank you for using our shipping calculator!")
main() # Calling main