The "TypeError: can't multiply sequence by non-int of type 'float'" error is thrown at us. This is happening because we cannot multiply a string and a floating point number or a tuple and a floating point number.
The result of the multiplication of a float and an int is a float . Besides that, it will get promoted to double when passing to printf . You need a %a , %e , %f or %g format. The %d format is used to print int types.
Use the multiplication operator to multiply an integer and a float in Python, e.g. my_int * my_float . The multiplication result will always be of type float .
for i in growthRates:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
should be:
for i in growthRates:
fund = fund * (1 + 0.01 * i) + depositPerYear
You are multiplying 0.01 with the growthRates list object. Multiplying a list by an integer is valid (it's overloaded syntactic sugar that allows you to create an extended a list with copies of its element references).
Example:
>>> 2 * [1,2]
[1, 2, 1, 2]
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])
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With