Python is an ideal programing language for creating web applications and websites. Programmers and developers use Python to build various applications extensively. It is an easy-to-program language that is written with simple syntax. The ease of coding makes it even more popular among beginners. When you are working with Python, you may experience “typeerror: ‘str’ object cannot be interpreted as an integer”.
How the error occurs
When you are creating a Python project, you land up in the error warning. This is what appears:
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
The script you tried:
x = input("Give starting number: ")
y = input("Give ending number: ")
for i in range(x,y):
print(i)
You may want to print something like the following assigning 3 to x and 14 to y:
Give starting number: 4
Give ending number: 13
4
5
6
7
8
9
10
11
12
13
After all this, you end up with the error warning. Let’s check out the next section to know how you simply fix the error
Solutions To Fix the Error “typeerror: ‘str’ object cannot be interpreted as an integer”
The range() accepts only integer values, and if it doesn’t have int as a parameter you are likely to get the TypeError. To help you out, we bring the best possible solutions to tackle the error. Take a look at them
Solution 1 – Parse String into an integer
The first option you can try out is to parse the string into an integer. You can do it like this
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)
You get a raw input (string) by input. Int is added, which is used to parse into an integer. You get an error as a result if no valid string is held by the string. You can even get it more refined with the help of try/except statements.
Solution 2 – Use int()
Another way to solve the error warning, you need to use int() in order to change the input. Use the following to remove this error:
x = int(input("Give starting number: "))
y = int(input("Give ending number: "))
for i in range(x, y):
print(i)
Output
Give starting number: 4
Give ending number: 13
4
5
6
7
8
9
10
11
12
Conclusion
We highlighted the solutions to remove the error “typeerror: ‘str’ object cannot be interpreted as an integer. You can simply implement the above solutions to resolve this TypeError. I hope you find it interesting and informative.
I wish you the best of luck!
Don’t feel shy if you need any assistance, just write a comment in the below comment box. We would love to help you!