125

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'
HaskellElephant
  • 9,819
  • 4
  • 38
  • 67
SD.
  • 3,089
  • 10
  • 26
  • 21

4 Answers4

103

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"))
tzot
  • 92,761
  • 29
  • 141
  • 204
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
79

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 
beta=1-alpha
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
Serendipity
  • 2,216
  • 23
  • 33
3

The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:

>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'

You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!

Eric Palakovich Carr
  • 22,701
  • 8
  • 49
  • 54
2

You can't multiply string and float.instead of you try as below.it works fine

totalAmount = salesAmount * float(salesTax)
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51
Maheshnagakumar
  • 43
  • 1
  • 1
  • 9