Home > Mobile >  In My Code There Is A Error Saying "Index Out Of Range" For Some Reason, I Actually Just S
In My Code There Is A Error Saying "Index Out Of Range" For Some Reason, I Actually Just S

Time:10-14

for w in 'words':
 if w[4] == 'z':
      print(w)

In This Code At line 3, it says :-

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    if w[4] == 'z':
IndexError: string index out of range

I can't Find A Solution To This, Please Try To Help

CodePudding user response:

it should be like this because in your code "for w in "words":" w represents the characters 'w','o','r','d','s' so if you are accessing the 'w'[4] It creates an error since there is no 4 the value in your character

for w in 'words':
 if w == 'z':
      print(w)

or you can have look on this

for w in range(len("words")):
  if words[w]=="z"
     print(words[w])

CodePudding user response:

Your code is not correct. You are trying to iterate the string words with w, so w is a character, but you are treating it like a list. You can try removing the for loop

if w[4] == 'z':
    print(w)

CodePudding user response:

Indexing is really valuable tool within python and many different programming languages. It allows you to select an element within a structure. Read here. Your problem is that you cannot index the 4th character of a string with a single character.

In your code example, you are looping through the string 'words' and at each iteration, the variable w is populated with the each letter. So, at the first iteration w is 'w', then 'o', then 'r', and so on. So when you are indexing the w variable, you are asking for a letter that doesn't exist.

Try:

for w in 'words':
   if w == 'z':
     print(w)
  • Related