user2899653
user2899653

Reputation: 71

Python TypeError: unsupported operand type(s) for /: 'str' and 'float'

My code:

total=tef+tpf-price

I've got this error:

  total=tef+tpf-price
unsupported operand type(s) for -: 'float' and 'str'

How do I fix it?

Upvotes: 0

Views: 104190

Answers (4)

Abhishek Das
Abhishek Das

Reputation: 111

Instead of this

total=tef+tpf-price

Try this, I hope this will help you

total=float(tef)+float(float)tpf-float(price)

Upvotes: 10

user2555451
user2555451

Reputation:

The only way that error could occur is if price is a string. Make price a float or an integer (depending on what you want) to fix the problem.

Either this:

tef=float(price)*5/100.0

or this:

tef=int(price)*5/100.0

Notice that, in Python, to preform an operation between two objects, those object must be of the same type (and support the operation of course).

Upvotes: 0

Mingyu
Mingyu

Reputation: 33349

I think you might take user's price input, like:

price = raw_input('--> ')    // Python 2.x

or

price = input('--> ')        // Python 3.x

So you might want to do some validation before using it.

You could cast price from string to float by float(price).

Upvotes: 2

ennuikiller
ennuikiller

Reputation: 46965

One simple way to fix it is:

tef=float(price)*5/100.0

Upvotes: 1

Related Questions