
This is a very specific TypeError that almost always happens in one place: the range() function. If you’ve seen the message “TypeError str object integer”, you’re probably wondering how to fix it.
It means: “You gave me a string (like “5”), but I need a real number (like 5) to know how many times to loop.”
The Cause
The range() function only accepts integers. This error is most common when you get a number from input(), which always gives you a string.
Problem Code:
num_times = input("How many times should I loop? ") # User types '10'
# 'num_times' is the STRING "10", not the NUMBER 10
for i in range(num_times):
print("Hello!")
# CRASH! TypeError: 'str' object cannot be interpreted as an integerThe Fix: Convert to int()
You must explicitly convert the string to an integer before you pass it to range().
num_times_str = input("How many times should I loop? ")
try:
num_times_int = int(num_times_str) # Convert "10" to 10
for i in range(num_times_int):
print("Hello!")
except ValueError:
print("That was not a valid number!")By wrapping the conversion in a try/except block, you also safely handle cases where the user types “hello” instead of a number.





