With the code below, no matter what the first letter of the input is, it is always determined as a vowel:
original = raw_input("Please type in a word: ")
firstLetter = original[0]
print firstLetter
if firstLetter == "a" or "e" or "i" or "o" or "u":
print "vowel"
else:
print "consonant"
In fact, it doesn't matter what the boolean is in the if statement... if it is == or != , it is still return "vowel"
. Why?
Your test doesn't work like you think it does. You are asking, "If the variable equals 'a'", then the rest of your test basically asks if the letters e, i, o or u are False. Only an empty string evaluates to False (try "e" == False in the interpreter to see). Use the "in" test from other answers. Also, make sure to lower-case firstLetter so you're always comparing like to like.
First you should know how
or
works, it evaluates both the left and right expression and it returns the first expression that evaluates true, otherwise it returns the last expression:From this source you can see that all of these evaluate false:
So a non-empty string will evaluate as true and it will be returned:
For a string
'foo'
,'f'
is the first letter. In the first part of your code,firstLetter == "a" or "e"
, the left expression will evaluate as false, but'e'
is not an empty string so it evaluates as true and it willprint "vowel"
You can see my other answer here which answers your question, something like this:
will check if a letter is a vowel.
what your test does is the following:
and each of the latter 4 tests is true.
Python is not the English language. If you have a bunch of expressions with
or
orand
between them, each one must make sense on its own. Note that on its own:will always print
something
, even ifletter
doesn't equal"e"
.You need to do it like this:
Or, more concisely:
Try this for your Boolean expression:
This is equivalent to
i.e., you want to put this into your if statement like this:
Note:
Your original approach was on the right track, but you would have had to compare each letter separetely like
Using the above is much more concise.