sutterhome1971
sutterhome1971

Reputation: 400

Exception: "can't multiply sequence by non-int of type 'float'

I'm trying to write very simple code to calculate the discount on a article. Following is the code and it throws the exception on the 3rd line in the code. The exception is:

Traceback (most recent call last):
  File "C:/Users/basam/AppData/Local/Programs/Python/Python35/discounts.py", line 3, in <module>
    discount=0.1*price
TypeError: can't multiply sequence by non-int of type 'float'

The code:

price=input('how much is your item?')
if int(price) <= 10:
    discount=0.1*price

Can someone advise on what the problem is?

Upvotes: 2

Views: 2199

Answers (3)

AlanK
AlanK

Reputation: 9853

As @Silvio Mayolo has stated, the problem is that your price variable is of type String. You can wrap your input() call to cast the input value to an integer which should allow for the calculation to work

price = int(input('how much is your item?'))
if price <= 10:
    discount = 0.1 * price

print(discount)
>> 0.5

or better yet - considering you're dealing with 'money' which can have decimal values, use a 'float' type rather than 'int'

price = float(input("how much is item 2?"))
if price <= 10:
    discount = 0.1 * price

print(discount)
>> 0.5

Upvotes: 2

mtrw
mtrw

Reputation: 35098

The key is int(price). The input command returns a string which is stored in the variable price.

In the second line, price is converted to a number by the call int(price), but that result is not stored anywhere. It is used for the comparison and then discarded. So when you go to multiply in the third line, you're trying to multiply a number times a string.

Upvotes: 5

Zichen Wang
Zichen Wang

Reputation: 1374

Change to discount=0.1*float(price)

Upvotes: -1

Related Questions