Python中的函数和循环复杂化

时间:2016-04-06 01:56:36

标签: python function while-loop main

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 ()

第一个功能的目的是允许用户在他或她想要的时间内输入以下内容,直到用户决定完成:

  1. 股票名称
  2. 购买的股票
  3. 售价
  4. 经纪佣金
  5. 我的主要问题是主要功能。我是否正确使用while循环或者它是否正确我持怀疑态度。我试图运行该程序,但它不会输出任何东西。

    另外,我不应该在程序结尾处添加这个值,并输入值来调用上面的所有函数:

    def main()
       load()
       calc()
       output()
    

    或者在while循环中是否正常?

1 个答案:

答案 0 :(得分:0)

我认为while循环非常适合这种用例,你需要循环不确定的次数,在不满足某些条件时停止。

这一行有一个明显的问题:

stockname +=1

这没有任何意义。由于stockname是一个字符串,因此您无法添加一个字符串。相反,您应该询问用户下一个股票名称(或者#34;特殊值"值,以表明他们已完成)。尝试用以下内容替换该行:

stockname = input("Enter the name of the next stock (or -999 to quit): ")

如果相当冗长,代码的其余部分显示正确。除非您认为您可能会在代码中的某个其他位置调用其他某些函数,否则将所有逻辑包含在一个函数中可能会更简单,更清晰。函数很好,但是你应该平衡将代码的每个部分隔离在自己的函数中的好处与在它们之间传递大量值的努力。