Search code examples
pythonindex-error

Index error in Python( index out of range)


given_number=str(input("Enter the number:"))
total=str(0)
num=0
while num<=len(given_number):
       total+=given_number[num]
       num+=1
print(total)  

Got indexerror.Where is the fault?


Solution

  • The problem is in your while loop. Apparently, your loop iterates through 0 to the length of your input string while the maximum index of 0 base list/array/string is

    len(given_number)-1

    Modify your code like this.

       given_number=str(input("Enter the number:"))
       total=str(0)
       num=0
       while num<len(given_number): # Note: I use < not <=
           total+=given_number[num]
           num+=1
       print(total)  
    

    I hope it will help you to overcome your problem.