Python TypeError: 'str' object cannot be interpreted as an integer Solution

Posted in /  

Python TypeError: 'str' object cannot be interpreted as an integer Solution
vinaykhatri

Vinay Khatri
Last updated on December 3, 2024

    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

    Python TypeError: 'str' object cannot be interpreted as an integer

    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.

    1. TypeError - The exception type
    2. 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:

    Leave a Comment on this Post

    0 Comments