[python] TypeError: 'str' object cannot be interpreted as an integer

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

Give starting number: 4
Give ending number: 13
4
5
6
7
8
9
10
11
12
13

What is the problem?

This question is related to python types

The answer is


You will have to put:

X = input("give starting number") 
X = int(X)
Y = input("give ending number") 
Y = int(Y)

You have to convert input x and y into int like below.

x=int(x)
y=int(y)

x = int(input("Give starting number: "))
y = int(input("Give ending number: "))

P.S. Add function int()


You are getting the error because range() only takes int values as parameters.

Try using int() to convert your inputs.


I'm guessing you're running python3, in which input(prompt) returns a string. Try this.

x=int(input('prompt'))
y=int(input('prompt'))

Or you can also use eval(input('prompt')).


x = int(input("Give starting number: "))
y = int(input("Give ending number: "))

for i in range(x, y):
    print(i)

This outputs:

i have uploaded the output with the code


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.