Python Forum
String index out of range - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: String index out of range (/thread-12289.html)



String index out of range - felie04 - Aug-17-2018

Hello,
I just started learning to code and I was doing my homework, I ran into an error.
The error is saying this:

Traceback (most recent call last):
File "/Users/daphne/Desktop/School Stuff/Computer science/IntroProg/Project/test3.py", line 8, in <module>
if nom[i] == char:
IndexError: string index out of range

I know it is related to my "nom[i]", but I don't know how to fix. If anyone could help me out, I would really appreciate!

Here is my code:
nom = input('Enter a name:')
length = len(nom)
i = 0
nb_e = 0
char = 'e'

while i <= length:
    if nom[i] == char:
        nb_e = nb_e + 1
    i = i + 1
print('Theres', nb_e, 'e')



RE: String index out of range - ichabod801 - Aug-17-2018

Python is 0-indexed. Therefore the maximum index of a string is the length of the string minus one. Your loop goes all the way to length, thus going out of range. This is one reason to avoid looping over indexes. Loop directly over the string:

for letter in nom:
   if letter == char:
       ...
Also, you should use more descriptive variable names. It makes your code easier to read and understand, like to the people you want help from.


RE: String index out of range - felie04 - Aug-17-2018

Thank you so much for the explanation!
Yes, also I will make sure next time my names are clearer so people can understand better my code, sorry about that! Smile