Why else changed the result?

I’m a beginner with python, doing now the chapter on strings. In exercise 10 I needed to write code, and after I did not manage to get the right answer, I ask for the solution. Then I compared it with my code, and I still do not understand why it did not work. The only difference is the part where I put else - can anyone explain to me what the difference is?

def letter_check1(word, letter):
  for i in word:
    if i == letter:
      return True
  return False
print(letter_check1("strawberry", "a"))   
def letter_check(word, letter):
  for i in word:
    if i == letter:
      return True
    else:
      return False
print(letter_check("strawberry", "a"))

The return statement causes your function to exit and hand back a value to its caller.

so by nesting else inside the loop, either letter argument equals the first letter of word or it doesn’t. based on only this first value of word true or false is handed back

1 Like

First of all, thank you for the quick answer.
So the problem is that I put the else inside the loop? So it checked only the first letter?

no, by putting else inside the loop you always get a return within the first iteration of the loop. Because either the first letter of word will equal letter, or it won’t. Either way a result is returned

otherwise to visualize the flow of the program:

http://www.pythontutor.com/visualize.html#mode=edit

might help

1 Like

Wow, that’s a great tool!
Now I understand. Thank you very much.

1 Like