【发布时间】:2016-07-26 04:57:00
【问题描述】:
def main():
totalprofit = 0
stockname = input("Enter the name of the stock or -999 to quit: ")
while stockname != "-999":
sharesbought, purchasingprice, sellingprice, brokercommission = load()
amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss = calc(sharesbought, purchasingprice, sellingprice, brokercommission)
output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofpaidcommission, profitorloss)
stockname = input("Enter the name of the next stock (or -999 to quit): ")
totalprofit += profitorloss
print("\n Total profit is: ", format(totalprofit, '.2f'))
def load():
sharesbought = int(input("Number of shares bought: "))
purchasingprice = float(input("Purchasing price: "))
sellingprice = float(input("Selling price: "))
brokercommission = float(input("Broker commission: "))
return sharesbought, purchasingprice, sellingprice, brokercommission
def calc(sharesbought, purchasingprice, sellingprice, brokercommission):
amountpaid = sharesbought * purchasingprice
amountofpaidcommission = amountpaid * (brokercommission/100)
amountstocksoldfor = sharesbought * sellingprice
amountofsoldcommission = amountstocksoldfor * (brokercommission/100)
profitorloss = (amountpaid + amountofpaidcommission) - (amountstocksoldfor - amountofsoldcommission)
return amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss
def output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss,):
print("\n Stock name: ", stockname, sep = '')
print("Amount paid for the stock: ", format(amountpaid, '.2f'))
print("Commission paid to broker when the stock was bought: ", format(amountofpaidcommission, '.2f'))
print("Amount the stock sold for: ", format(amountstocksoldfor, '.2f'))
print("Commission paid to broker when the stock was sold: ", format(amountofsoldcommission, '.2f'))
print("Profit or loss: ", format(profitorloss, '.2f'))
main ()
第一个功能的目标是允许用户根据需要多次输入以下内容,直到用户决定完成:
- 股票名称
- 购买的股票
- 售价
- 经纪人佣金
我的主要问题是在 main 函数中。我怀疑我是否正确使用了while循环或者它是否正确。我试图运行该程序,但它不会输出任何内容。
另外,我不应该在程序末尾添加这个并输入值来调用上面的所有函数:
def main()
load()
calc()
output()
或者在while循环中可以吗?
【问题讨论】:
-
将
main()添加到代码的最底部 -
您在 while 条件中检查
stockname,但用户只能在 while 循环之前输入 。从来没有,所以一旦设置了stockname,它将永远保持这种状态。您可能想在 while 底部附近向用户询问新的stockname。 -
同样在第 18 行你使用
brokercommision而你应该使用brokercommission(缺少一个 s) -
在第 25 行,你使用
amountstockssoldfor,而你应该使用amountstocksoldfor -
感谢您发现错误。更新。 @Racialz,我将主要内容移至底部。我应该将它与 while 循环一起移动吗?
标签: python function while-loop main