Strings and Conditional Part One (python)

Hello, I would like to ask why the code doesn’t work when I’m using “else”:

def letter_check(word, letter):
  for x in word:
    if x == letter:
      return True
    else:
      return False
    
    
print(letter_check("HOLYWOOD", "L"))

The result it shows is “False”. I cannot get it.

Remember that return returns a value, and then halts the function. That means that the first time return is reached, execution of the function ceases. The way your function is written, if letter were “H”, it would return True; any other letter will return False.

Are you trying to return True if letter is anywhere in the word, and False otherwise? If so, one way (there are many) would be to start out with a variable set to False. If the letter is present, change the variable to True, then, after all the letters have been run through, return the variable.

1 Like