37

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?

Mel
  • 5,837
  • 10
  • 37
  • 42
Joe
  • 371
  • 1
  • 3
  • 3

8 Answers8

33

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.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
10

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

Try using int() to convert your inputs.

Rahul
  • 161
  • 2
  • 6
4
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

Dadep
  • 2,796
  • 5
  • 27
  • 40
irshad
  • 41
  • 2
3
x = int(input("Give starting number: "))
y = int(input("Give ending number: "))

P.S. Add function int()

1

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

x=int(input('prompt'))
y=int(input('prompt'))
Perkins
  • 2,409
  • 25
  • 23
1

You will have to put:

X = input("give starting number") 
X = int(X)
Y = input("give ending number") 
Y = int(Y)
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
MafiaCure
  • 65
  • 1
  • 1
  • 11
1

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

x=int(x)
y=int(y)
SPradhan
  • 67
  • 1
  • 8
1

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

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
  • eval() will convert the expression to an evaluated version of the input.This is used to counter the backward non-compatiblity of python 3 against Python 2. – Aditya Kumar Feb 06 '17 at 06:59
  • I used this in my program for factorial which was not working before(error given was : for i in range(1,n+1): TypeError: must be str, not int) and it worked: n = eval(input("Enter a number: ")) j=1 for i in range(1,n+1): j=j*i i=i+1 print(j) – Aditya Kumar Feb 06 '17 at 07:01
  • This may work... But it creates an enormous security flaw, an attacker has quite literally free reign when you run eval like this without first properly checking the string... – 255.tar.xz Mar 25 '20 at 17:26