Reputation: 408
I am a python learner. I'm trying to find a retirement funds simulator that takes three arguments: a salary (salary
), a percentage of your salary to save (save
), and a list of annual growth percentages on investments (growthRates
). The length of the last argument defines the
number of years you plan to work; growthRates[0]
is the growth rate of the first year, growthRates[1]
is the growth rate of the second year, etc.
on running program I'm having this error:
TypeError: can't multiply sequence by non-int of type 'float'
The code I've written is:
def ret_fund():
a = int(input("Enter Salary: "))
b = int(input("Enter Saving Percentage: "))
c = list(input("Enter List of Growth Rates per Year (must be zero for first year): "))
ans_list=[]
x = 1
global x
for i in c:
float(i)
x = x*(1+0.01*i)+(a*b*0.01)
ans_list.append(x)
print (ans_list)
I just can't figure out the error. Help me with that please.
what about variable c
? it doesn't actually take a list
as an input as demanded by the program. I have to enter numbers like 05643
and they get picked one by one. what if I want to give input like [0, 5, 6, 4, 3]
?
Upvotes: 2
Views: 1110
Reputation: 308402
The problem is with the global x
, which overrides the local assignment of x
. I'm assuming the global x
is a list of some kind.
Edit: A previous version of this answer contained incorrect code for reading the growth rates.
To read a list of growth rates you should read it as a single string, split the string, and convert each piece. The input
method doesn't do the right thing on its own.
c = raw_input("Enter List of Growth Rates per Year (must be zero for first year): ")
for i in c.split():
i=float(i)
Upvotes: 2
Reputation: 12950
The statement float(i)
does nothing. Either use i=float(i)
, or substitute i
in your formula with float(i)
, since it appears only once.
Depending on what the user enters, input()
will return a corresponding object. If you enter 0.0, 1.0, 2e10, 99
you already get a tuple of float and integer values, so there is no reason to convert anything, because, for example, 0.01*x
will be converted to floating point in any case. Example:
>>> a=input("enter numbers: ")
enter numbers: 1,2,3.0, 5e-10, 99
>>> print type(a), repr(a)
<type 'tuple'> (1, 2, 3.0, 5e-10, 99)
>>> for i in a: print i, type(i)
...
1 <type 'int'>
2 <type 'int'>
3.0 <type 'float'>
5e-10 <type 'float'>
99 <type 'int'>
>>> for i in a: print 0.01*i, type(0.01*i)
...
0.01 <type 'float'>
0.02 <type 'float'>
0.03 <type 'float'>
5e-12 <type 'float'>
0.99 <type 'float'>
Upvotes: 2