In today’s tutorial we’ll learn how to troubleshoot a common error typically encountered by newcomers to the Python programming language: trying to use a string containing numeric values as an integer.
Problem – Str cannot be interpreted as int in Python
Look carefully into the code below (you can better follow along by copying this to you Python development tool of choice (Idle, Spyder, Jupyter, PyCharm, VSCode etc’):
# define a variable and get input from the user num_iterations = input ('enter number of iterations:') # use the variable as a range in a for loop for i in range(num_iterations): print (i)
This will obviously result in an type error. The input function receives a string. Our short program goes ahead and tries to interpret it as an integer – that won’t work. Here’s a screenshot from my Jupyter Lab Notebook:
Solution – cast your input to use it in the loop
We can get rid of this type error by making a very simple modification to our program. We’ll cast the user input (which as we mentioned before, is a string) to an integer data type. Then we will go ahead and use that integer as a range in our for loop. The changes to the program are demarcated in bold characters:
num_iterations = int (input ('enter number of iterations:')) for i in range(num_iterations): print (i)
This will work as expected. In our case list all numbers from 0 to 99 included.