Raihaan-Tech
Raihaan-Tech

Reputation: 5

What is IndexError? I keep Getting It

Here is my code:

quote = input("Enter a Sentence: ")

a = len(quote)
counter = 0
counter1 = 0
reverse = a

print("The Length of the sentence is",a,"characters long!")

for x in range(0,a):
    if str.isspace(quote[x]) == True:
        counter = counter + 1

print("The Length of the sentence is",a - counter,"characters long (excluding space...)!")

for x in range(0,a):
    if str.isupper(quote[x]) == True:
        counter1 = counter1 + 1

print("The number of Upper Case Characters in the sentence is",counter1,"characters!")

print("The number of Lower Case Characters in the sentence is",a-counter1,"characters long!\n")


while reverse >= 1:
    r = reverse
    print(quote[r])
    r = r - 1

It's aim is to find everything about that sentence, but the only problem is the 'While' loop at the bottom. It doesn't seem to work, and it's aim is to 'inverse' the sentence. However, it gives my an error which looks a bit like this:

Traceback (most recent call last):
  File "C:\Documents and Settings\ususer\My Documents\Downloads\StringStuff.py", line 27, in <module>
    print(quote[r])
IndexError: string index out of range

What Am I doing wrong? Please help!

Upvotes: 0

Views: 167

Answers (2)

leeladam
leeladam

Reputation: 1758

You have run into the common problem that Python starts indexing from 0, but returns the lenght of a list as a valid integer counted from 1. This results that for any list, l[len(l)] will give you IndexError, because a list of length 10 will only have indexes 0...9. All you have to do is to initialize reverse = len(quote)-1. You also have to descend your loop variable inside the while loop, so use reverse-=1 instead of r=r-1.

Upvotes: 0

Xymostech
Xymostech

Reputation: 9850

Python is 0-indexed, so the first character of a string is str[0] and the last is str[len(str) - 1]. So, since you start with reverse = len(quote), at the end you are doing quote[len(quote)], which is one past the end of the string.

So, you should probably start with reverse = a - 1 and your loop at the end should look something like:

while reverse >= 0:
    print(quote[reverse])
    reverse = reverse - 1

Upvotes: 3

Related Questions