【发布时间】:2017-02-22 19:44:23
【问题描述】:
我是编程新手。我已经编写了 4 个基本程序,现在我正在学习函数。我正在尝试制作一个使用功能的运输和处理程序,但我被卡住了。描述如下:编写一个应用程序,计算产品的总成本,包括运输、处理和税收。这应该除了main之外还有3个函数。
第一个函数要求用户输入其订单的小计并将此信息返回给 main。这些值必须经过验证。小计必须至少为 1 美元且不超过 9,999 美元。
第二个函数计算运输成本和处理成本,然后将此信息返回给 main。运费为订单成本的 10%。例如,10 美元订单的运费为 1 美元。对于 100 美元以下的订单,处理费为 2 美元。否则,处理是免费的。
第三个函数计算 6% 的销售税并将此信息返回给 main。销售税仅基于小计,而不基于运费或装卸费。
然后,Main 将在屏幕上显示此信息,如下例所示。 (必须传递和返回值)。
输出应如下所示:
Product Total Information
Subtotal $300.00
Shipping $30.00
Handling $0.00
Sales tax $18.00
Grand total $348.00
这是我目前所拥有的: 请记住,我对此完全陌生。这是我的主要内容:
def main():
subtotal = calc_subtotal
tax = calc_tax
shipping = calc_shipping
handling = calc_handling
print('subtotal: ')
print('Shipping: ')
print('Handling: ')
print('Sales tax: ')
print('Grand total: ')
为了小计验证,我写了一个 if/else 语句:
def calc_subtotal():
subtotal = float(input('Enter your subtotal please: '))
if subtotal >= 1 and subtotal <= 9999:
print('This is a valid amount')
else:
print('Invalid amount')
return subtotal
现在我想我必须做一些简单的事情来计算税额,例如: 小计 * .06
从方向的书写方式来看,运输和装卸计算似乎可以在同一个函数中完成?
我正在努力解决的部分是如何让小计值转到其他功能?就像税收函数一样,我需要做的就是将它乘以 0.06,但我不知道如何将它调用到该函数中。我知道这很长,您可能有很多我可能无法回答的问题,但如果您愿意提供帮助,我将不胜感激。感谢阅读。
这是截至 2017 年 2 月 23 日的更新程序代码:
def main():
print('This will calculate shipping, handling and taxes on your purchase')
subtotal = calc_subtotal()
tax = calc_tax()
shipping = calc_shipping()
handling = calc_handling()
total = calc_total()
print('subtotal: ', subtotal)
print('Shipping: ', shipping)
print('Handling: ', handling)
print('Sales tax: ', tax)
print('Grand total: ', total)
def calc_subtotal():
subtotal = float(input('Enter your subtotal please: '))
if subtotal >= 1 and subtotal <= 9999:
print('This is a valid amount')
else:
print('Invalid amount')
return subtotal
def calc_tax():
subtotal = calc_subtotal()
tax = subtotal + subtotal * .06
return tax
def calc_handling():
subtotal = calc_subtotal()
if subtotal < 100:
print('There is a 2 dollar handling fee')
else:
print('There is no handling fee')
def calc_shipping():
subtotal = calc_subtotal()
shipping = subtotal + subtotal * .10
print('Your shipping cost is: ', shipping)
def calc_total():
total = subtotal + shipping + handling + tax
main()
【问题讨论】:
-
请修正您的代码缩进,以便我们确定您的尝试。
-
好的,我想我现在已经把所有东西都排好了。
-
subtotal = calc_subtotal不调用calc_subtotal,它使subtotal成为对calc_subtotal函数的引用。subtotal = calc_subtotal()将调用 makesubtotal引用从calc_subtotal()返回的结果。然后,您可以定义将该值作为参数的其他函数。 -
要让其他功能正常工作,我需要在 main 中添加一些东西吗?还是应该自动完成其余功能?当我现在运行它时,它会循环到 1-9999 之间的数字的小计验证并显示打印消息。感谢您的帮助,我正在缓慢但肯定地学习这些东西。
-
这是一个程序,所以它只会做你告诉它做的事情。您所描述的“循环”不是循环,它只是从一个功能到另一个(然后返回)的普通控制流。如果您希望调用其他函数,则必须按照您希望它们发生的顺序编写这些调用。如果您是编程新手以及 python 新手,spronck.net/pythonbook 可能会有所帮助。 openbookproject.net/thinkcs/python/english3e 也很贴心。
标签: python