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 ()
第一个函数的目标是允许用户输入以下内容,直到用户决定完成为止:
我的主要问题是主函数。我怀疑我是否正确使用while循环,或者它是否正确。我试着运行这个程序,但它什么也不输出。你知道吗
另外,我不应该在程序的末尾添加这个值来调用上面的所有函数吗
def main()
load()
calc()
output()
或者在while循环中可以吗?你知道吗
我认为
while
循环非常适合这个用例,在这个用例中,您希望循环不确定的次数,在某些条件不满足时停止。你知道吗在这条线上有一个明显的问题:
这没有任何意义。因为
stockname
是一个字符串,所以不能向其中添加一个。相反,您应该要求用户输入下一个股票名称(或者一个“特殊”值来表示他们已经完成了)。尝试用以下内容替换该行:其余的代码看起来是正确的,尽管相当冗长。除非您认为可能会在代码中的其他位置调用其他函数,否则在一个函数中包含所有逻辑可能会更简单、更干净。函数很好,但是您应该平衡将代码的每个部分隔离在自己的函数中的好处与在它们之间传递大量值的努力。你知道吗
相关问题 更多 >
编程相关推荐