Why does this script not return true with the given statements when it obviously should be true?

Here is the code from the Strings module I used:

def letter_check(word,letter):

count = 0

index = 0

while count <= len(word):

for i in word[index]:

  if i == letter:

    return True

    index += 1

    count += 1

  elif i != letter:

    return False

    continue

print(letter_check(“strawberry”,“a”))

In my mind this should NOT return false.

Anything after return is unreachable. Consider the placement of your return statements.

1 Like

It looks like you’re on the right track, but you’ve got one or two issues in there.

Firstly, remember return exits the function. So, on your first loop you’re checking i (which will be ‘s’) against letter(‘a’), it’s returning with false and that’s where it’s ending.
Think, do you really need to be checking if it’s false at each stage. We know it’ll be false if it’s got through the loop and not been found true.

Secondly, you’ve got two loops trying to do the same thing. The while loop is effectively incrementing the index (be careful with your indenting, or you might get stuck in an infinite loop).
The for loop is setup wrong. In python, ‘for i in word’ will track through word one character at a time ( you don’t need to put [index] on the end - that will just loop through the single character at whatever index is )
So, in the for loop i would track ‘s’, ‘t’, ‘r’, …etc
as would word[count] when going through the while loop.

Hope that’s a help. Feel free to reply if you’re still not sure about any of it.

I understand what you’re saying, thank you so much!

1 Like