TypeError:' float'使用sum时,object不可迭代

时间:2016-12-23 04:48:18

标签: python python-2.7

我正在尝试获取从expenses_calc函数获得的返回值的总和,但我正面临" TypeError:' float'对象不可迭代"。我需要做出哪些更改才能解决此错误?

from nsetools import Nse
    nse = Nse()

#Name of stocks and buy prices
stocks = {
    "APLAPOLLO": 878.2,
    "AVANTIFEED": 488.95,
    "BALAMINES": 308.95
}

#Quantity of stocks
qty = {
    "APLAPOLLO": 10,
    "AVANTIFEED": 10,
    "BALAMINES": 10
}

def get_closing(stock):
    """
    Function to obtain closePrice of stocks
    """
    return nse.get_quote(stock)['buyPrice1']

def expenses_calc(buy,sell,qty):
    """
    Function to calculate the applicable expenses
    """
    stt = 0.10
    ttc = 0.00325
    service_tax = 15.0
    sebi_charges = 0.0002
    swacch_bharat_cess = 0.02
    stamp_duty = 0.01

    turnover = (buy * qty) + (sell * qty)
    stt_total = (stt / 100) * turnover
    total_tran_charge = (ttc / 100) * turnover
    service_tax = (service_tax / 100) * total_tran_charge
    sebi_charges = (sebi_charges / 100) * turnover
    stamp_duty = (stamp_duty / 100) * turnover
    total_tax_and_charges = stt_total + total_tran_charge + service_tax + sebi_charges + stamp_duty
    total_investment = buy * qty
    current_value = sell * qty
    net_profit = (sell * qty) - (buy * qty) - total_tax_and_charges
    return net_profit

#For loop that calls the expenses_calc function in a loop with the right arguments
for key in stocks.keys():
    buy_price = stocks[key]
    sell_price = get_closing(key)
    stock_qty = qty[key]
    expenses_func_call = expenses_calc(buy_price, sell_price, stock_qty)
    print(sum(expenses_func_call))

发生类型错误的行

print(sum(expenses_func_call))

我尝试创建一个空的myresults列表,然后将expense_calc函数的返回值附加到它,然后打印列表的总和,这也不起作用。

for key in stocks.keys():
    myresults = []
    buy_price = stocks[key]
    sell_price = get_closing(key)
    stock_qty = qty[key]
    expenses_func_call = expenses_calc(buy_price, sell_price, stock_qty)
    myresults.append(expenses_func_call)
    print(sum(myresults))

2 个答案:

答案 0 :(得分:1)

除了上一个答案之外,您还需要将列表传递给sum函数,因此您最初尝试纠正问题是正确的。但是您应该在进入循环之前初始化myresults列表。目前,每次执行循环时,您实际上都会覆盖myresults内容。

答案 1 :(得分:0)

在下次尝试将值附加到列表myresults时,您的print语句应该在for循环之外