Search code examples
pythonlistloopstkintertreeview

Trouble in multiplying list of numbers converted from string to float in a loop (Python)


Here I am trying to multiply numbers stored in a list but in string type, showing this error

TypeError: can't multiply sequence by non-int of type 'float'

My list data sample

[5, 'BTCUSD', 'Sell', '9125.5', 6055, '0.66352527', 'Limit', 'Filled']

def calc():
num=0.0
den=0.0
for ids in listBox.selection():
    num=num+(float(listBox.item(ids)['values'][3]*float(listBox.item(ids)['values'][4]))) #Problem occurng here
    den=den+float((listBox.item(ids)['values'][4]))
    print(listBox.item(ids)['values'])
    print(num/den)
return 0

Solution

  • I might need more information about listBox,
    but as I roughly see the given code, I think the line which caused error should be edited like below:

    # Original Code:
    #   num=num+(float(listBox.item(ids)['values'][3]*float(listBox.item(ids)['values'][4])))
        num=num+(float(listBox.item(ids)['values'][3])*float(listBox.item(ids)['values'][4]))
    


    TypeError: can't multiply sequence by non-int of type 'float'

    This occurs literally when you're trying to multiply a sequence(list, string, etc) with a float value like:

    a = 'hello'
    print(a * 3.0)  # error
    

    Multiplying a sequence by integer value is allowed, and it functions as repeating the sequence n times:

    a = 'hello'
    print(a * 3)   # 'hellohellohello'
    

    In your code, you didn't finished first float() function correctly. The second float() function is well done, so you were just trying to multiply a string (which is not converted yet) with a float value (which is converted well). Please inspect the parenthesis in your code carefully. Thanks.