Detecting Vowels vs Consonants In Python [duplicate]

空扰寡人 提交于 2019-11-27 05:12:06

Change:

if first == "a" or "e" or "i" or "o" or "u":

to:

if first in ('a', 'e', 'i', 'o', 'u'):  #or `if first in 'aeiou'`

first == "a" or "e" or "i" or "o" or "u" is always True because it is evaluated as

(first == "a") or ("e") or ("i") or ("o") or ("u"), as an non-empty string is always True so this gets evaluated to True.

>>> bool('e')
True

What you are doing in your if statement is checking if first == "a" is true and then if "e" is true, which it always is, so the if statement always evaluates to true.
What you should do instead is:

if first == "a" or first == "e" ...

or better yet:

if first in "aeiou":

Your issue is that first == "a" or "e" is being evaluated as (first == "a") or "e", so you're always going to get 'e', which is a True statement, causing "vowel" to be printed. An alternative is to do:

original = raw_input('Enter a word:')
word = original.lower()
first = word[0]

if len(original) > 0 and original.isalpha():
    if first in 'aeiou':
        print "vowel"
    else:
        print "consonant"
else:
    print "empty"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!