How is this incorrect yet the simple test I posted reveal that it is indeed the correct output? Reason I did it offline that way is to show that it is the test that is failing on a correct output.
This because you below code is iterating on word for each letter and in doing so it first takes the first first letter of word and matching it (because of if statement) with letter argument passed to function if it matches then it is going to read the code block inside if statement and since it find to return True so it return True and then breaking the loop. On contrary, if in the very first iteration, the first letter of word don’t matches with letter argument then it directly jumps to else statement and it return False. You need to thing the execution steps of your code then you’ll easily understand. Hope it helps.
The CA system didn’t like it, and I saw their answer had a lot more steps:
def letter_check(word, letter):
for character in word:
if character == letter:
return True
return False
Since my code worked, is there a reason why we need to include the “for” line in here? Are there some cases I’m not thinking of where my code wouldn’t work?
One could suggest the author is still giving the learner practice with loops , conditionals and return. The first example should not be returning string objects. Boolean primitives are not strings, as we see in the second example.
Truth is we don’t need the loop, nor the conditional, nor the literals, just a boolean expression…
Remember that once a return statement is executed, the function is immediately exited. This means that any other code in the function will not be run once a return statement occurs. Can you see the problem in your code? Hint: Your loop currently only goes through 1 iteration no matter what the result of the if statement is.