level: beginner
why do i get error "can't multiply sequence by non-int of type 'float'"?
def nestEgVariable(salary, save, growthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
for i in growthRates:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
SavingsRecord += [fund,]
return SavingsRecord
print nestEgVariable(10000,10,[3,4,5,0,3])
thanks Baba
This question is related to
python
floating-point
sequence
In this line:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
I think you mean this:
fund = fund * (1 + 0.01 * i) + depositPerYear
When you try to multiply a float by growthRates (which is a list), you get that error.
In this line:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
growthRates is a sequence ([3,4,5,0,3]
). You can't multiply that sequence by a float (0.1). It looks like what you wanted to put there was i
.
Incidentally, i
is not a great name for that variable. Consider something more descriptive, like growthRate
or rate
.
Because growthRates is a sequence (you're even iterating it!) and you multiply it by (1 + 0.01), which is obviously a float (1.01). I guess you mean for growthRate in growthRates: ... * growthrate
?
Python allows for you to multiply sequences to repeat their values. Here is a visual example:
>>> [1] * 5
[1, 1, 1, 1, 1]
But it does not allow you to do it with floating point numbers:
>>> [1] * 5.1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i
to rate
and using that instead. See the updated code below:
def nestEgVariable(salary, save, growthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
# V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
for rate in growthRates:
# V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
fund = fund * (1 + 0.01 * rate) + depositPerYear
SavingsRecord += [fund,]
return SavingsRecord
print nestEgVariable(10000,10,[3,4,5,0,3])
Source: Stackoverflow.com