简体   繁体   中英

Python - checking for vowels, code returns false no matter what

I am a beginner, so I apologize if this question seems too simple. I don't know where to go from here with my code, so that it works correctly. Any suggestions on where to go from here would be very much appreciated!

Thank you.

def isVowel(word, i):
for i in word:
    if i == 'a' or i == 'e' or i == 'i' or i == 'o' or i =='u' or i == 'y':
        return True
    else:
        return False

this is how i planned on executing it:

[isVowel('detestable', i) for i in range(len('detestable'))]
[False, False, False, False, False, False, False, False, False, False]

as you can see, I continue to get false as the result. I have tried a few different things, and I keep getting all false or all true.

UPDATE

I thought I had already tried this, but

def isVowel(word, i):
    if word[i] == 'a' or word[i] == 'e' or word[i] == 'i' or word[i] == 'o' or word[i] =='u' or word[i] == 'y':
        return True
    else:
        return False

works perfectly. Feel free to continue to add suggestions, as I'm sure there are more effective ways to write this code.

From the usage example, it seems as though isVowel should only evaluate a single character, not a word:

def isVowel(i):
    return i in 'aeiou'

And in practice:

>>> [isVowel(i) for i in 'detestable']
[False, True, False, True, False, False, True, False, False, True]

I was about to post the same as @Mureinik.

Here's a little different version.

>>> is_vowel = lambda v: v in 'aeiou'
>>> word = 'detestable'
>>> [is_vowel(ch) for ch in word]
[False, True, False, True, False, False, True, False, False, True]
>>> 

So my interpretation is you want to get a list of booleans for every letter if it is one of these letters aeiuoy :

def is_vowel(word):
    return [letter in 'aeiuoy' for letter in word]

used like that:

is_vowel('foobar')
-> [False, True, True, False, True, False]

so my recommendation for you would be to check out the i in the function isVowel(word, i): because it is actually overwritten by usage of i the for loop for i in word: . And I would recommend freshing up your knowledge about functions and scopes in python + python list comprehensions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM