-1

I can't figure out why when I enter the word 'fish' for original its printing vowel.

#Begin program

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    word = original.lower() #make sure original is lowercase
    first = word[0]
    if first == 'a' or 'e':
        print "vowel"
    else:
        print "consonant"
else:
    print 'empty'

4 Answers4

3
if first == 'a' or 'e'

Change it to

if first == 'a' or first == 'e':

Or

if first in ('a', 'e'):

Your if statement is evaluating to True since you are doing a boolean OR with a True value ('e').

Non empty strings in Python evaluate to True.

>>> bool('')
False
>>> bool('a')
True

Hence, your code gets evaluated as

if (first == 'a') or True:

which is always evaluated to True and hence the if statement is executed.

Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
2

Your if condition is wrong. Specifically,

if first == 'a' or 'e':

won't work. It needs to be

if first == 'a' or first == 'e':

The original statement evaluates like this:

if (first == 'a') or ('e'):

if (False) or (True):

Here's an explanation of truth values in Python. Note that characters evaluate as true.

thegrinner
  • 11,546
  • 5
  • 41
  • 64
1

It's because if first == 'a' or 'e': is being treated like if (first == 'a') or ('e'):

Since 'e' is truthy, the or is returning true

StephenTG
  • 2,579
  • 6
  • 26
  • 36
1

To avoid such situations and to make your code more clear, write

if first in ('a', 'e'):
    ...

or

if first in 'ae':
    ...
gukoff
  • 2,112
  • 3
  • 18
  • 30