Tuesday, 5 July 2016

string - Detecting Vowels vs Consonants In Python





What silly mistake am I making here that is preventing me from determining that the first letter of user input is a consonant? No matter what I enter, it allows evaluates that the first letter is a vowel.



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

if len(original) > 0 and original.isalpha():
if first == "a" or "e" or "i" or "o" or "u":
print "vowel"
else:

print "consonant"
else:
print "empty"

Answer



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...