Why the code is not working if I put else part under the same if indentation?

Hi , my code doesn’t work when i use else part under the same if indentation line:

def letter_check(word, letter):
  for character in word:
    if character == letter:
      return True
    else:
        return False
  return False

print(letter_check("strawberry", "a"))

But if I do like this , it works , please explain me the difference,

def letter_check(word, letter):
  for character in word:
    if character == letter:
      return True
  return False

print(letter_check("strawberry", "a"))

the first code sample, you don’t really have a loop. The first character of word is compared to the letter, based on this comparison True or False is returned

in the second example, if at any point the character equals the letter, true is returned. If this doesn’t happen (letter not in word), false is returned

return means handing back data to the caller, signaling the function is done executing.

but second code sample doesn’t even have else part, how it is working?

How to fix it in my first code sample?

It works because it doesn’t have any other value to compare. So it keeps comparing each character with letter.

While your first code basically says “check character to letter if it’s equal say true, if don’t then say false” But as the first character isn’t equal to letter then is false and the code finishes. So here you have to ask yourself, how do you have to write your code to make it compare every letter before saying False or True. Maybe with a counter, maybe saving the character in a list, maybe using a pass or break statement

1 Like

you could use for/else. But it doesn’t really matter flow wise. Either way, if no return is reached within the loop (condition always false), the last return statement (return False) is reached

1 Like