Python 中的函数和 While 循环复杂化

Functions And While Loop Complication In Python

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

第一个功能的objective是允许用户多次输入以下内容,直到用户决定完成:

  1. 股票名称
  2. 购买的股票
  3. 售价
  4. 经纪人佣金

我的主要问题是在 main 函数中。我怀疑我是否正确使用了 while 循环,或者它是否正确。我尝试 运行 该程序,但它不会输出任何内容。

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

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

或者在 while 循环中可以吗?

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

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

stockname +=1

这没有任何意义。因为 stockname 是一个字符串,所以不能加一。相反,您应该询问用户下一个股票名称(或 "special" 值以表示他们已完成)。尝试用以下内容替换该行:

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

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