Python 类型错误:“str”对象不能解释为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19234598/
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
TypeError: 'str' object cannot be interpreted as an integer
提问by Joe
I don't understand what the problem is with the code, it is very simple so this is an easy one.
我不明白代码有什么问题,它很简单,所以这是一个简单的。
x = input("Give starting number: ")
y = input("Give ending number: ")
for i in range(x,y):
print(i)
It gives me an error
它给了我一个错误
Traceback (most recent call last):
File "C:/Python33/harj4.py", line 6, in <module>
for i in range(x,y):
TypeError: 'str' object cannot be interpreted as an integer
As an example, if x is 3 and y is 14, I want it to print
例如,如果 x 是 3,y 是 14,我希望它打印
Give starting number: 4
Give ending number: 13
4
5
6
7
8
9
10
11
12
13
What is the problem?
问题是什么?
回答by BartoszKP
A simplest fix would be:
最简单的解决方法是:
x = input("Give starting number: ")
y = input("Give ending number: ")
x = int(x) # parse string into an integer
y = int(y) # parse string into an integer
for i in range(x,y):
print(i)
input
returns you a string (raw_input
in Python 2). int
tries to parse it into an integer. This code will throw an exception if the string doesn't contain a valid integer string, so you'd probably want to refine it a bit using try
/except
statements.
input
返回一个字符串(raw_input
在 Python 2 中)。int
尝试将其解析为整数。如果字符串不包含有效的整数字符串,则此代码将引发异常,因此您可能希望使用try
/except
语句对其进行细化。
回答by Perkins
I'm guessing you're running python3, in which input(prompt)
returns a string. Try this.
我猜你正在运行 python3,其中input(prompt)
返回一个字符串。尝试这个。
x=int(input('prompt'))
y=int(input('prompt'))
回答by MafiaCure
You will have to put:
你必须把:
X = input("give starting number")
X = int(X)
Y = input("give ending number")
Y = int(Y)
回答by SPradhan
You have to convert input x and y into int like below.
您必须将输入 x 和 y 转换为 int ,如下所示。
x=int(x)
y=int(y)
回答by Aditya Kumar
Or you can also use eval(input('prompt'))
.
或者您也可以使用eval(input('prompt'))
.
回答by Ливиу Греку
x = int(input("Give starting number: "))
y = int(input("Give ending number: "))
P.S. Add function int()
PS 添加功能 int()
回答by irshad
x = int(input("Give starting number: "))
y = int(input("Give ending number: "))
for i in range(x, y):
print(i)
This outputs:
这输出:
回答by Rahul
You are getting the error because range() only takes int values as parameters.
您收到错误是因为 range() 仅将 int 值作为参数。
Try using int() to convert your inputs.
尝试使用 int() 来转换您的输入。