Python 类型错误:不支持 / 的操作数类型:'str' 和 'str'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15235703/
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-18 19:36:06  来源:igfitidea点击:

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

pythontypeerroroperand

提问by Deric miller

name = input('Enter name here:')
pyc = input('enter pyc :')
tpy = input('enter tpy:')
percent = (pyc / tpy) * 100;
print (percent)
input('press enter to quit')

whenever i run this program i get this

每当我运行这个程序时,我都会得到这个

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

what can i do to divide pyc by tpy?

我该怎么做才能将 pyc 除以 tpy?

采纳答案by Martijn Pieters

By turning them into integers instead:

通过将它们转换为整数:

percent = (int(pyc) / int(tpy)) * 100;

In python 3, the input()function returns a string. Always. This is a change from Python 2; the raw_input()function was renamed to input().

在 python 3 中,该input()函数返回一个字符串。总是。这是对 Python 2 的改变;该raw_input()函数已重命名为input().

回答by Bryan Oakley

The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.

您应该做的第一件事是学习阅读错误消息。它告诉您什么 - 您不能将两个字符串与除法运算符一起使用。

So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.

因此,问问自己为什么它们是字符串,以及如何使它们成为非字符串。它们是字符串,因为所有输入都是通过字符串完成的。制作非字符串的方法是转换它们。

One way to convert a string to an integer is to use the intfunction. For example:

将字符串转换为整数的一种方法是使用int函数。例如:

percent = (int(pyc) / int(tpy)) * 100

回答by Kovalchuk

I would have written:

我会写:

percent = 100
while True:
     try:
        pyc = int(input('enter pyc :'))
        tpy = int(input('enter tpy:'))
        percent = (pyc / tpy) * percent
        break
     except ZeroDivisionError as detail:
        print 'Handling run-time error:', detail