Check whether a character is a vowel or consonant in Python
Understanding Vowels and Consonants
A vowel is a letter (a, e, i, o, u) that represents an open speech sound. A consonant is any other letter in the alphabet.
We will explore three different methods to check whether a character is a vowel or consonant in Python.
Method 1: Using if-else
This method checks if the character belongs to the set of vowels.
def check_vowel_or_consonant(ch):
if ch.lower() in 'aeiou':
print(f"{ch} is a vowel")
else:
print(f"{ch} is a consonant")
ch = input("Enter a character: ")
check_vowel_or_consonant(ch)
Output: a is a vowel
Method 2: Using Match Case
This method uses a match case (Python 3.10+) to determine if the character is a vowel.
def check_vowel_or_consonant(ch):
match ch.lower():
case 'a' | 'e' | 'i' | 'o' | 'u':
print(f"{ch} is a vowel")
case _:
print(f"{ch} is a consonant")
ch = input("Enter a character: ")
check_vowel_or_consonant(ch)
Output: b is a consonant
Method 3: Using Recursion
This method checks vowels recursively.
def is_vowel(ch):
return ch.lower() in 'aeiou'
def check_vowel_or_consonant(ch):
if is_vowel(ch):
print(f"{ch} is a vowel")
else:
print(f"{ch} is a consonant")
ch = input("Enter a character: ")
check_vowel_or_consonant(ch)
Output: o is a vowel