快速提问:
我想在不带任何参数的情况下调用一个main函数,在main函数中,我还有其他几个函数有参数。我该怎么做呢?
以下是多个功能:
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the total price of the shares at time of purchase
def total_purchase_price(portfolio):
totalprice = 0
totalpurprice = 0
for item in portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += purprice * numshares
totalpurprice = totalprice
return totalpurprice
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the current total value of the shares
def total_value(portfolio):
totalprice = 0
totalvalueprice = 0
for item in portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += curprice * numshares
totalvalueprice = totalprice
return totalvalueprice
# Takes the previous two functions, and subtracts them to get the total
# gain/lost of the shares
def total_gain(total_purchase_price, total_value, portfolio):
gainlost = total_value - total_purchase_price
return gainlost
例如,我现在所拥有的(注意:我知道这是行不通的,只是为了我想要的,因为每个函数都返回一个值):
def testQ1(total_purchase_price, total_value, total_gain, portfolio):
print("Total Cost =", total_purchase_price)
print("Current Value =", total_value)
print("Total gain/lost =", total_gain)
return
例如,我想实现的目标:
def testQ2():
total_purchase_price(portfolio)
total_value(portfolio)
total_gain(total_purchase_price, total_value, portfolio)
print("Total Cost =", total_purchase_price)
print("Current Value =", total_value)
print("Total gain/lost =", total_gain)
return
我该怎么做?谢谢
portfolio是testQ2中唯一没有计算的参数。你需要有一个全局值,或者读入(可能在另一个函数中)。计算后,按适当的顺序返回值。
使用类可能更容易:
然后你可以这样使用它:
相关问题 更多 >
编程相关推荐