Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Kristin Wilson
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')):
.
Here is an example of how the error occurs.
# 👇️ this is a string my_num = '5' # ⛔️ TypeError: 'str' object cannot be interpreted as an integer for i in range(my_num): print(i)
We passed a string to the range()
constructor which expects an integer
argument.
To solve the error, pass the string to the int()
constructor to convert it to
an integer.
my_num = '5' for i in range(int(my_num)): print(i)
The error often occurs when getting user input using the built-in input()
function.
# 👇️ this is a string num = input('Enter your fav number: ') print(num) print(type(num)) # 👉️ <class 'str'> # ⛔️ TypeError: 'str' object cannot be interpreted as an integer for i in range(num): print(i)
The input function converts the data to a string and returns it.
To solve the error, pass the result to the int()
constructor.
num = input('Enter your fav number: ') print(num) print(type(num)) # 👉️ <class 'str'> # ✅ Convert str to integer for i in range(int(num)): print(i)
The int class returns an integer object constructed from the provided number or string argument.
The constructor returns 0
if no arguments are given.
print(int('10')) # 👉️ 10 print(int('5')) # 👉️ 5
The range constructor
is commonly used for looping a specific number of times in for
loops and takes
the following parameters:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
If you only pass a single argument to the range()
constructor, it is
considered to be the value for the stop
parameter.
Make sure you aren't declaring a variable that stores an integer initially and overriding it somewhere in your code.
my_int = 10 # 👇️ reassigned variable to a string by mistake my_int = '30' # ⛔️ TypeError: 'str' object cannot be interpreted as an integer for i in range(my_int): print(i)
We initially set the my_int
variable to an integer but later reassigned it to
a string which caused the error.