view raw
Wiggs Wiggs - 8 months ago 20
Python Question

If else statement for finding the index of a character in a string

For some reason without the else statement the code finds the indexes of the characters in the string. However, when I add the else statement to declare if a character is not found. All it does is give me the else statement even if the character is in the string.

#Function takes a character and a string and returns the index of the character
#found in the string.
def whereIsItS(letter, word):
#Start finding the index of characters in the string starting at 0.
letInWord = 0
#For loop to find specific characters in a string.
for l in word:
#If the letter is found it returns the index of the letter.
if l == letter:
#Moves to the next character in the string.
letInWord += 1
return "It is not there."
#Returns the index of the character found the string.
return word.index(letter)

I just can't seem to figure out why it works without the else statement, but not with the else statement.

Jim Jim

return will always exit from a function and not continue any loops you are performing.

You either print it's not there but that wouldn't even be true because you're printing for the current letter.

This is relatively simple to achieve with the following:

def whereIsItS(letter, word):
    if letter in word:
        return word.index(letter)
        return "Letter {0} not in word {1}".format(letter, word)

If the letter is in the word, return its index, if not, return the message specifying it wasn't found.

Further trimmed with a conditional expression to:

def whereIsItS(letter, word):
    return word.index(letter) if letter in word else "Letter {0} not in word {1}".format(letter, word)