Trying to add 1 to a function but getting the error "can't multiply sequence by non-int of type 'float'"

Viewed 34

I'm trying to add 1 to a function

def capital_final(p,r,n):
   s=p*(1+r)**n  
   print('El capital final es:', round(s,2))  
   return s


p=input('Capital inicial: ')
P=float(p)
r=input('Tasa de interés: ')
r=float(r)
n=input('Numero de periodos: ')
n=float(n)
capital_final(p,r,n)

But I keep getting this error

TypeError                                 Traceback (most recent call last)
<ipython-input-142-f80bd70e7ed3> in <module>()
      6 n=float(n)
      7 
----> 8 capital_final(p,r,n)

<ipython-input-141-2dc9cecbb82d> in capital_final(p, r, n)
      6   return p
      7 def capital_final(p,r,n):
----> 8   s=p*(float(1)+r)**n
      9   print('El capital final es:', round(s,2))
     10   return s

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

You mistakenly wrote

P = float(p)

it should be

p = float(p)

Lowercase p variable is the string read in by input. You can't multiply that by a float.

p=input('Capital inicial: ')
P=float(p)

creates two variables; one identified by a lowercase p, one identified by an uppercase P. p remains a string, which you then pass into the function. To resolve, lowercase the left hand side in the assignment of the second variable:

p=input('Capital inicial: ')
p=float(p)
Related