Q: Finding first vowel of a word in Python so I am having trouble finding the index of the first vowel of a inputted string. When putting in the string "elephant" , "hello" , "spa" they work properly, however when I input "spam" it does not work, it returned the number 3 instead of 2. I am having trouble finding why it satisfies the else statement but not the initial if condition. I am also trying to put a condition that if there are no vowels in the string, then it should print out the index of the last character in the string. Below is my code:
def find_first_vowel(word):
    i = 0   
    while i < len(word):
        i+= 1
        if word[i] in vowels:
            return i
        else:
            return len(word)-1
    return i

print(find_first_vowel("spam"))   


A: Your code always return len(word)-1 if the character in position 1 is not a vowel. Also elephant didn't work and spa works only because of the bug I mentioned, it returns 2 which is len(word)-1 and not the index of the vowel found. Try debug your code line by line and you'll figure it out very quickly.
This could be a working code that return -1 if there's no vowel, else return the index of the first vowel found.
def find_first_vowel(word):
    i = 0   
    while i < len(word):
        if word[i] in vowels:
            return i
        i += 1
    return -1

EDIT
If you want to return the last character if there's no vowels just change return -1 with return len(word) - 1. Here:
def find_first_vowel(word):
    i = 0   
    while i < len(word):
        if word[i] in vowels:
            return i
        i += 1
    return len(word) - 1


A: You should use enumerate to handle tracking the index for you
vowels = set('aeiou')

def find_first_vowel(word):
    for index, letter in enumerate(word):
        if letter in vowels:
            return index
    return index  # Returns last index if no vowels.  You could also return None, or raise an error


A: Either return statement jumps out of your while loop immediately, without looking at the rest of the word. Additional problem: since you start with i += 1, the function never even looks at the first character, which would be word[0].
I think your main issue is that you meant for your else statement to be executed if the while loop completed and exited without finding a vowel. As indented, though, it's part of the if statement in the while loop, and executes whenever the second character isn't a vowel. You want something more like this:
i = 0
while i < len(word):
    if word[i] in vowels:
        return i
    i += 1

And then whatever you want the function to return if the word has no vowels.
