Why do I get TypeError: can't multiply sequence by non-int of type 'float'?


I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount).

I run into this error. Anyone know what could be wrong or have any suggestions?

salesAmount = raw_input (["Insert sale amount here \n"])
['Insert sale amount here \n']20.99
>>> salesTax = 0.08
>>> totalAmount = salesAmount * salesTax

Traceback (most recent call last):
  File "<pyshell#57>", line 1, in <module>
    totalAmount = salesAmount * salesTax
TypeError: can't multiply sequence by non-int of type 'float'
9/28/2012 12:31:29 AM

Accepted Answer

raw_input returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3 is "ABABAB"; how much is "L" * 3.14 ? Please do not reply "LLL|"). You need to parse the string to a numerical value.

You might want to try:

salesAmount = float(raw_input("Insert sale amount here\n"))
1/28/2009 1:10:29 AM

Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the * operator on a list.

For example:

import math
import numpy as np
alpha = 0.2 
C = (-math.log(1-beta))/alpha

coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C

The error:

    coff *= C 
TypeError: can't multiply sequence by non-int of type 'float'

The solution - convert the list to numpy array:

coff = np.asarray(coff) * C

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow