Python TypeError:不支持的操作数类型/:'str'和'float'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19480060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:52:03  来源:igfitidea点击:

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

pythontypeerror

提问by user2899653

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?

我如何解决它?

回答by user2899653

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

可能发生错误的唯一方法是 ifprice是一个字符串。将 price 设为浮点数或整数(取决于您想要的)以解决问题。

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).

请注意,在 Python 中,要在两个对象之间执行操作,这些对象必须是相同类型的(并且当然支持操作)。

回答by ennuikiller

One simple way to fix it is:

修复它的一种简单方法是:

tef=float(price)*5/100.0

回答by Mingyu

I think you might take user's priceinput, like:

我认为您可能会接受用户的price输入,例如:

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 pricefrom string to float by float(price).

您可以price从 string 转换为 float by float(price)

回答by Abhishek Das

Instead of this

而不是这个

total=tef+tpf-price

Try this, I hope this will help you

试试这个,我希望这会帮助你

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