Home > Software engineering >  How do I check each letter in a word is either a vowel or consonant?
How do I check each letter in a word is either a vowel or consonant?

Time:02-03

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.

CodePudding user response:

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"))

CodePudding user response:

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")))

CodePudding user response:

The code you have written will not return the desired result as it is missing a return statement for the case where the character is in the second set of letters (consonants). The current implementation will return None for all inputs as there is no return statement after the loop.

Here's a corrected version of the code:

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

print(check_v_c("Money"))

This code will return the first vowel in the input word if one is present, and "Consonant" otherwise.

  • Related