Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 749
Joe Avatar asked Oct 07 '13 20:10

Joe


People also ask

How do you fix str object Cannot be interpreted as an integer?

The Python "TypeError: 'str' object cannot be interpreted as an integer" occurs when we pass a string to a function that expects an integer argument. To solve the error, pass the string to the int() constructor, e.g. for i in range(int('5')): .

How do you convert string to integer in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .


2 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.

like image 59
BartoszKP Avatar answered Sep 27 '22 00:09

BartoszKP


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

Try using int() to convert your inputs.

like image 31
Rahul Avatar answered Sep 26 '22 00:09

Rahul