Hamza Khatib
Hamza Khatib

Reputation: 39

How do I check each letter in a word is either a vowel or consonant?

def check_v_c(word):
    for i in word:
        if i in "AEIOUaeiou":
            return i

        else:
            i in "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"


print(check_v_c("Money"))

I was trying to loop each letter using the for loop.

Upvotes: 0

Views: 153

Answers (3)

Shady Emad
Shady Emad

Reputation: 86

  • you need to change return i to print(f"{i} is vowel") which will print something like that (o is vowel)

  • and if the first condition is False the letter will be consonant so you need to change i in "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz" to print(f"{i} is consonant") which will print something like that (m is consonant)

  • if you don't understand the format i use to print, i suggest you to check this

  • To optimize the code: use word.lower() which will reduce the number of comparisons.

def check_v_c(word):
    # Make a for loop and convert the input to lowercase to reduce the number of comparisons
    for i in word.lower():
        if i in "aeiou":
            print(f"{i} is vowel")
        else:
            print(f"{i} is consonant")

print(check_v_c("Money"))

you can see output here

Upvotes: 0

Muhammad Ali
Muhammad Ali

Reputation: 489

I hope, this will work for your solution use string class to check for punctuation

import string
def check_v_c(word):
    result = []
    for i in word:
        if i.lower() in "aeiou":
            result.append(f'{i} is a vowel')
        elif i in string.punctuation:
            result.append(f'{i} is a punctuation')
        else:
            result.append(f'{i} is a consonant')
    return result
print('\n'.join(check_v_c("Mon.ey")))

Upvotes: 2

Adarsh Gupta
Adarsh Gupta

Reputation: 55

You only need to remove else as if if is False the it will run for loop again

def check_v_c(word):
  for i in word:
    if i in "AEIOUaeiou":
        return i


print(check_v_c("Money"))

But if you want to pass something then you can

def check_v_c(word):
  for i in word:
    if i in "AEIOUaeiou":
        return i

    else:
        "It is not vowel"


print(check_v_c("Money"))

Upvotes: 1

Related Questions