-2

I'm new to Python and have written a program that determines if a letter in a string entered is a vowel or consonant. If the letter is a vowel the program prints 'vowel' but if a consonant it prints the consonant.

I've written the program in two different ways and cannot figure out why the second code set doesn't work. When run it returns 'vowel' for all letters in the string entered.

#this code works
word = input("Please enter a word: ")
for letter in word.lower():
    if letter == 'a':
        print("vowel")
    elif letter == 'e':
        print("vowel")
    elif letter == 'i':
        print("vowel")
    elif letter == 'o':
        print("vowel")
    elif letter == 'u':
        print("vowel")
    else:
        print(letter)

#this code doesn't work

word = input("Please enter a word: ")
for letter in word.lower():
    if letter == 'a' or 'e' or 'i' or 'o' or 'u':
        print("vowel")
    else:
        print(letter)

If I input 'David' in first code set it returns [d, vowel, v, vowel, d]. I'm wondering why the logic in the 'for' statement of the second set of code doesn't work. Why can I not use the comparison operator 'or' the way I have it in the second code sample? When the second set of code is run I get is the word 'vowel' returned for all letters in the string

  • The "if" statement of your second code sample is a bit flawed - each of your "or" tests after the first one returns true...try using "if letter in ['a','e','i','o','u']" – ccbunney Jan 24 '19 at 14:55

1 Answers1

0

So there you have a confusion, in python bolean can be quite confusing. empty list, empty char will evaluate to False. non empty list and char will evaluate True.

# when your are doing :
if letter == 'a' or 'e' or 'i' or 'o' or 'u':

you are testing if letter =='a' but if 'e' is a non empty char. The correct form is :

if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o': # continue

here you test each case both the first way and second way are equivalent.

RomainL.
  • 997
  • 1
  • 10
  • 24