Typeerror: 'Str' Object Cannot Be Interpreted as an Integer [Duplicate]

Typeerror: 'Str' Object Cannot Be Interpreted as an Integer [Duplicate]

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?

0

8 Answers

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.

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

Try using int() to convert your inputs.

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

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

This outputs:

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

P.S. Add function int()

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

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

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

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

You will have to put:

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

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

3
David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.