Why doesn't `else: return False` work?

Why in the context of this exercise the following code isn’t correct:

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

I was forced to look for a solution, but I still don’t quite understand why they skipped -else- line and then unindented -return False-.

6 Likes

As the code is written above it exits the function on the first iteration in all cases.

19 Likes

Thanks for your answer sir. Unfortunately, I still didn’t quite understand. :confused: Does it exit the function after checking if character == letter and thus deciding if returning True or not returning True? If so, does it mean that it doesn’t even consider returning False (in a code written this way)?

I apologize for any misunderstanding from my side.

2 Likes

Because the conditional has an else clause, it will leave the function in either case, match or no match. Remove the else: return False from the loop so that it only returns a True from within the loop, otherwise the loop continues to completion. Once outside of the loop that means no matches were found, anywhere. The default return of the function will be False.

42 Likes

Processing halts when any return statement is executed (whichever it may be.) Program control passes to the calling expression (along with the return value), so no expression following return is executed; the function and its variables essentially disappear.

28 Likes

Hi ai-2090

The answers above are absolutely correct, but I thought I will word it the way I understood, as I wrote the exact same code first and amended it after encountering incorrect output.

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

line one >>
> for character in word:

The py compiler read this to iterate through the word ‘strawberry’ (as in the exercise)

line two>>
> if character == letter:

Compiler is doing check for ‘s’ == word (in exercise-case ‘a’)
So ‘s’ == ‘a’ , which is not true

So compiler skips ‘return True’, and moves to else statement, where
‘s’ == ‘a’, is False, so else statement holds true, therefore compiler picks return False output.

As soon as a return statement is accepted by the compiler, it exits the code and return the output it accepted from all that iterating. It never even got a chance to compare rest of the word that is, ‘trawberry’, as compiler found a output that fulfilled a condition in the code.

That’s why for the iteration condition to read the whole word ‘strawberry’ we just remove else statement and return False code from the for loop. The compiler now iterates through all of the word and if if statement with return True condition is not satisfied, it comes out of the loop with None output , then reads return False, and so gives the desired output. :slightly_smiling_face:

228 Likes

the step by step explanations was wonderful.
thanks

2 Likes

This explanation is perfect. thanks a lot

That helped. Once it returns a true statement iteration is done…Unless else is included. The function continues to iterate at that time, finding an else scenario, and returns false.
Thanks!

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

sorry little misunderstanding here. How does this code stop the Return False “overriding”’ the return True statement. It seems like it would iterate through return True and then immediately return False and change the value to False.

it is not clear that if statement when returning its value, if it does, exists the for loop and will not simply move on to the return false statement

see I would have written this instead

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

I am so confused how this return False statement is somehow working, and not messing up the whole code. How does it not just get executed and change the value.

Does python read the Return False statement after an iterative Boolean check differently: i.e this return false statement is only executed if the return true statement is not. Therefore, this is a special case of a return False statement where it acts slightly different because of the conditional boolean check.

3 Likes

It is not overriding, but rather the default outcome if the loop completely iterates over the word without finding a matching character. Note that return False is not inside the loop.

If a match is found the function is exited with a True return.

  for character in word:
    if character!= letter:
      return False

That would be unnecessary, given the first loop was able to complete iteration. The only conclusion we could draw (logically) is that no match was found so the only possible return at that point is False.

1 Like

Thank you @patrickd314, I think that makes sense to me. I was wondering the same thing.

Would a “continue” command work to help the process going? Or does that not work after a return statement either?

No. The continue command would never be reached. return is the end of the line, and of the function and its local variables.

You can only “keep the process going” by proper placement of return, i.e., at the place where you want the process to stop.

Okay, thank you! I’m still hazy with this, if I were to do it on my own. I supposed stuff like this gets easier as I do it more often.

1 Like

Here are some examples:

def vowel_check(word):
    '''return True if word contains any vowel,
    otherwise return False
    '''
    for character in word:
        if character in 'aeiou':
            return True
    return False

def vowel_count(word):
    '''return the number of vowels
    contained in word
    '''
    count = 0
    for character in word:
        if character in 'aeiou':
            count += 1
    return count

print(vowel_check('aardvark'))
print(vowel_count('aardvark'))
print(vowel_check('psst'))
print(vowel_count('psst'))

Output:

True
3
False
0

Try them out! Move return to different indentation levels.

6 Likes

my friend, don’t forget what return does. It ends the programm. In this case, the programme operates in these steps:

  1. Checks the first character of the word.
    a. if its the same as the letter, it returns True.
    b. if its not, it returns False.

As long as the programme returns a value, it stops.

Thats why it doesn’t work, because you haven’t ordered it to continue to the next character if the first one doesn’t meet the target letter.

Hope this helps!!!

Happy coding :slight_smile:

14 Likes

I never knew that return ends a program! Lightbulb moment!

return exits the function which then terminates. The program is still running, one expects.

1 Like

Why don’t we use - else: - here?

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

1 Like

Because when you do character == letter, it will only check the first character. It has to do with understanding return statements. When you have a return statement the loop will stop. For example:
if you are checking if the letter “m” is in ice-cream, your code will do this:

Loop through first character. The character does not equal to letter(“m”). Now it it will move to the else statement which is False. Now it will return False and end the loop.

Say you now want to search for “i” in ice-cream, you would start with the first character and check if it is “i.” If your code runs, it will see that the first character is I and return True. Now your answer is True which is technically correct and your entire loop would stop because of return statement.

This is why it would be a good idea to use continue which is what I did. I will let you try to play with that. I am not sure how codecademy solved that question though

5 Likes