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,79710 gold badges37 silver badges42 bronze badges
asked Oct 7, 2013 at 20:56
0
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.
answered Oct 7, 2013 at 20:57
BartoszKPBartoszKP
34.6k14 gold badges101 silver badges129 bronze badges
You are getting the error because range() only takes int values as parameters.
Try using int() to convert your inputs.
answered Jun 10, 2019 at 11:20
Rahul Rahul
1612 silver badges6 bronze badges
x = int(input("Give starting number: "))
y = int(input("Give ending number: "))
for i in range(x, y):
print(i)
This outputs:
Dadep
2,7965 gold badges27 silver badges40 bronze badges
answered Sep 25, 2018 at 5:27
x = int(input("Give starting number: "))
y = int(input("Give ending number: "))
P.S. Add function int()
answered Dec 7, 2017 at 10:33
I’m guessing you’re running python3, in which input(prompt)
returns a string. Try this.
x=int(input('prompt'))
y=int(input('prompt'))
answered Oct 7, 2013 at 20:58
PerkinsPerkins
2,38924 silver badges22 bronze badges
1
You have to convert input x and y into int like below.
x=int(x)
y=int(y)
answered Dec 19, 2015 at 6:38
SPradhanSPradhan
671 silver badge8 bronze badges
You will have to put:
X = input("give starting number")
X = int(X)
Y = input("give ending number")
Y = int(Y)
BartoszKP
34.6k14 gold badges101 silver badges129 bronze badges
answered Oct 7, 2013 at 21:02
MafiaCureMafiaCure
651 gold badge1 silver badge11 bronze badges
Or you can also use eval(input('prompt'))
.
BartoszKP
34.6k14 gold badges101 silver badges129 bronze badges
answered Feb 6, 2017 at 6:57
3
Python range() function can only accept integer values as arguments. If we try to pass a string number value as an argument, we receive the error
»
TypeError: 'str' object cannot be interpreted as an integer
»
.
If you encounter the same error while executing a Python program and don’t know why it occurs and how to resolve it, this article is for you.
This Python tutorial discusses »
TypeError: 'str' object cannot be interpreted as an integer
» in detail. It helps you understand this error with a typical example of where you may encounter it in your program.
Python range() Function
Python provides a function called range() that returns a sequence of numbers, starting from 0 by default, in a given range. It accepts three parameters — start, stop, and step.
-
Start
— The start value of a sequence. -
Stop
— The next value after the end value of a sequence. -
Step
— It is an integer value denoting the difference between two consecutive numbers in a sequence.
This method is primarily used with
Python for loop
. Here is an example of how the range() function works:
even_numbers = range(0, 10, 2)
for n in even_numbers:
print(n)
Output
0
2
4
6
8
When you use a string value in the range() function, you get the error
TypeError: 'str' object cannot be interpreted as an integer
.
If the range() method accepts a string value, it will be quite confusing for the Python interpreter to determine what range of numbers should be displayed. Hence, passing integer values as arguments to the range() function is necessary.
Error Example
even_numbers = range(0, '10', 2)
for n in even_numbers:
print(n)
Output
Traceback (most recent call last):
File "/home/main.py", line 1, in <module>
even_numbers = range(0, '10', 2)
TypeError: 'str' object cannot be interpreted as an integer
In this example, we received the error because the second argument in the
range(0,
'10'
, 2)
function is a string.
By reading the error statement,
TypeError: 'str' object cannot be interpreted as an integer
, we can conclude why Python raised this error.
Like a standard error statement, this error also has two sub-statements.
-
TypeError
— The exception type -
The ‘str’ object cannot be interpreted as an integer
— The error message
We receive the TypeError exception becaue the range function excepts the value of the
int
data type, and we passed a string. And the error message ‘
str' object cannot be interpreted as an integer
clearly tells us that the Python interpreter can not use the value of the string data type, as it only accepts an integer.
Example
Let’s discuss a common case where you may encounter the above error in your Python program.
Let’s say we need to write a program that prints all the prime numbers between 1 to n, where n is the last number of the series.
Program
#function that check if the number is a prime number or not
def is_prime(num):
for i in range(2,num):
if num % i ==0:
return False
return True
#input the number upto which we want to find the prime numbers
n = input("Enter the last number: ")
print(f"Prime numbers upto {n} are:")
for i in range(2,n):
if is_prime(i):
print(i)
Output
Enter the last number: 12
Prime numbers upto 12 are:
Traceback (most recent call last):
File "main.py", line 12, in
for i in range(2,n):
TypeError: 'str' object cannot be interpreted as an integer
Break the Code
The above error indicates that there is something wrong with the statement
for i in range(2,n)
. The error message states that the value
n
is not an integer. Hence, throws the TypeError exception.
Solution
Whenever we accept input from the user, it is always stored in string data type. If we want to pass that input data into a function like
range()
, we first need to convert it into an integer using the
int()
function.
#function that check if the number is a prime number or not
def is_prime(num):
for i in range(2,num):
if num % i ==0:
return False
return True
#input the number upto which we want to find the prime numbers
#and convert it into integer
n = int(input("Enter the last number: "))
print(f"Prime numbers upto {n} are:")
for i in range(2,n+1):
if is_prime(i):
print(i)
Output
Enter the last number: 12
Prime numbers upto 12 are:
2
3
5
7
11
Now, our code runs smoothly without any errors, and we get the desired output.
Conclusion
The Error
TypeError: 'str' object cannot be interpreted as an integer
is very common when we deal with the Python range() function. This error occurs when we pass a string value to the range() function instead of integers. The most common case is when we input the data from the user and use the same data with the range function without converting it into an integer.
If you still get this error in your Python program, please send your query and code in the comment section. We will try to help you as soon as possible
.
People are also reading:
-
List Comprehension in Python
-
Python List
-
How to Declare a List in Python?
-
Python Directory
-
File Operation
-
Python Exception
-
Exception Handling
-
Anonymous Function
-
Python Global, Local and Nonlocal
-
Python Arrays
I am writing a code where the program draws the amount of cards that was determined by the user. This is my code:
from random import randrange
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self.ranks = [None, "ace", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "jack", "queen", "king"]
self.suits = {"s": "spades","d": "diamonds","c": "clubs","h": "hearts"}
def getRank(self):
return self.rank
def getSuit(self):
return self.suit
def __str__(self):
return "%s of %s" % (self.ranks[self.rank], self.suits.get(self.suit))
def draw():
n = input("Enter the number of cards to draw: ")
for i in range(n):
a = randrange(1,13)
b = randrange(1,4)
c=Card(a,b)
print (c)
draw()
And this is the error I keep getting:
Traceback (most recent call last):
File "main.py", line 31, in <module>
draw()
File "main.py", line 24, in draw
for i in range(n):
TypeError: 'str' object cannot be interpreted as an integer
Any help would be appreciated.
If you are getting trouble with the error “TypeError: ‘str’ object cannot be interpreted as an integer”, do not worry. Today, our article will give a few solutions and detailed explanations to handle the problem. Keep on reading to get your answer.
Why does the error “TypeError: ‘str’ object cannot be interpreted as an integer” occur?
TypeError is an exception when you apply a wrong function or operation to the type of objects. “TypeError: ‘str’ object cannot be interpreted as an integer” occurs when you try to pass a string as the parameter instead of an integer. Look at the simple example below that causes the error.
Code:
myStr = "Welcome to Learn Share IT" for i in range(myStr): print(i)
Result:
Traceback (most recent call last)
in <module>
----> 3 for i in range(myStr):
TypeError: 'str' object cannot be interpreted as an integer
The error occurs because the range()
function needs to pass an integer number instead of a string.
Let’s move on. We will discover solutions to this problem.
Solutions to the problem
Traverse a string as an array
A string is similar to an array of strings. As a result, when you want to traverse a string, do the same to an array. We will use a loop from zero to the length of the string and return a character at each loop. The example below will display how to do it.
Code:
myStr = "Welcome to Learn Share IT" for i in range(len(myStr)): print(myStr[i], end=' ')
Result:
W e l c o m e t o L e a r n S h a r e I T
Traverse elements
The range()
function is used to loop an interval with a fix-step. If your purpose is traversing a string, loop the string directly without the range()
function. If you do not know how to iterate over all characters of a string, look at our following example carefully.
Code:
myStr = "Welcome to Learn Share IT" for i in myStr: print(i, end=' ')
Result:
W e l c o m e t o L e a r n S h a r e I T
Use enumerate() function
Another way to traverse a string is by using the enumerate()
function. This function not only accesses elements of the object but also enables counting the iteration. The function returns two values: The counter and the value at the counter position.
Code:
myStr = "Welcome to Learn Share IT" for counter, value in enumerate(myStr): print(value, end=' ')
Result:
W e l c o m e t o L e a r n S h a r e I T
You can also get the counter with the value like that:
myStr = "Welcome to Learn Share IT" for counter, value in enumerate(myStr): print(f"({counter},{value})", end= ' ')
Result:
(0,W) (1,e) (2,l) (3,c) (4,o) (5,m) (6,e) (7, ) (8,t) (9,o) (10, ) (11,L) (12,e) (13,a) (14,r) (15,n) (16, ) (17,S) (18,h) (19,a) (20,r) (21,e) (22, ) (23,I) (24,T)
Summary
Our article has explained the error “TypeError: ‘str’ object cannot be interpreted as an integer” and showed you how to fix it. We hope that our article is helpful to you. Thanks for reading!
Maybe you are interested:
- UnicodeDecodeError: ‘ascii’ codec can’t decode byte
- TypeError: string argument without an encoding in Python
- TypeError: Object of type DataFrame is not JSON serializable in Python
My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.
Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP
Typeerror: ‘str’ object cannot be interpreted as an integer error occurs while typecasting str object into int type if the str objects are not numerical convertible. If there is any alphabet or special characters in the string then we can not typecast the str object to integer type object. In this article, we will explore the best ways to fix this Typeerror.
For better understanding lets replicate this error. Just run the below code to replicate the issue.
start="a1"
end="a3"
for i in range(start,end):
print(i)
In the above code, we use str in the place of int type object hence if we run this code we will get this error (‘str’ object cannot be interpreted as an integer). We can solve this error in multiple ways.
Solution 1 : Cleaning the str object and make integer compatible –
This type of solution is applicable if because of wrong code implementation unexpected str object is coming. For example, suppose you are fetching the roll number from Database but by logic error , the name and roll number both are coming all together. In such type of case we can clean the input before processing and make it integer compatible.
Solution 2 : Typecasting from str to int –
If the str is compatible with int type of object then there is no requirement of cleaning we can directly convert the same into int() type. In the above example we did cleaning + typecasting and here we need to do typecasting only.
Solution 3 : Using (try -except) for handling exception –
Suppose if you do not want to brake the program flow and just need to build a separate path for exceptions. Then use this try-catch block for handling these type of situation. Please follow the below code.
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Something went wrong.