0

So its fairly simple. Given a string I want to print out all the letters grammatically correct. With 'an' with vowels and 'a' in all other letters.

I cant seem to do that right now.

my_name = 'Alexander'

for l in my_name:
    if l in "A" or "e" or "i" or "o" or "u": 
        print("give me an " + l + " !")
    else:
        print('give me a '+l +" !") 

Problem: All the letters are printed out with an "an"

Navy Seal
  • 125
  • 1
  • 14

3 Answers3

1

Your problem is that every time you use or you need a separate conditional. Otherwise, you are simply evaluating "e" which is always True.

Just check if it is in a list like so:

my_name = 'Alexander'

for l in my_name:
    if l.lower() in ["a", "e", "i", "o", "u"]: #str.lower() is to check regardless of capitalization
        print("give me an " + l + " !")
    else:
        print('give me a '+l +" !")

If you check the boolean value of a string, it is always True:

>>> bool("e")
True
>>> 

And so the code would always enter the if.


>>> for l in my_name:
...     if l.lower() in ["a", "e", "i", "o", "u"]: #str.lower() is to check regardless of capitalization
...         print("give me an " + l + " !")
...     else:
...         print('give me a '+l +" !")
... 
give me an A !
give me a l !
give me an e !
give me a x !
give me an a !
give me a n !
give me a d !
give me an e !
give me a r !
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
0

Change your code to this.

my_name = 'Alexander'

for l in my_name:
    if l.lower() in ["a","e","i","o","u"]:
        print("give me an " + l + " !")
    else:
        print('give me a '+l +" !")

You need to check if the letter is in an array of characters. If you want a boolean expression then the if condition will have to be

if l == "A" or l == "e" or l == "i" or l == "o" or l == "u":
Curious
  • 20,870
  • 8
  • 61
  • 146
0

It is printing it because the condition if l in "A" or "e" or "i" or "o" or "u": always returns last character "u" and therefore condition goes to true so to solve this you have to write it like this,

if l in "A" or l in "e" or l in "i" or l in "o" or l in "u":

or you can also write it like this in list,

if l in ["A","e","i","o","u"]:
Dharmik
  • 445
  • 3
  • 10