Codecademy Exercise on Strings and Conditionals:
Write a function called letter_check
that takes two inputs, word
and letter
.
This function should return True
if the word
contains the letter
and False
if it does not.
def letter_check(word, letter):
for character in word:
if (character.upper() == letter or character.lower() == letter):
return True
else:
return False
print(letter_check("Woolly Mammoth", "m"))
I do not understand why my code is giving the output as False. Can someone please explain what I am doing wrong here?
The else part is the problem.
For each iteration, it returns True
or False
… which is a problem
because the return ends the function and the loop at that moment,
so it would never go past checking the first letter.
You want it to continue checking the next letter if that letter is not the same,
so you shouldn’t have return False
in the else block,
because that would stop the loop from getting to the next letter.
hint
return False
should not be inside the loop;
it should be after the loop.
(You don’t need the else.)
As the answer above correctly stated, the else block is not needed here (and will likely be reported by static analysis tools
).
Actually the entire for loop and the if statement are not needed. A concise and readable way of implementing this is using the ‘in’ keyword to check for membership:
def letter_check(word, letter):
return letter.upper() in word.upper() # Assuming capitalization doesn't truly matter
print(letter_check("Woolly Mammoth", "m"))
Thank you. I understand it now.
Thank your for explaining.