Q.1 - Write a Python program to test whether a passed letter is a vowel or not
ANSWER
Complete Python Solution:
def is_vowel(letter):
# Convert to lowercase for easier comparison
letter = letter.lower()
# Check if the letter is a vowel
if letter in ['a', 'e', 'i', 'o', 'u']:
return True
else:
return False
# Get input from user
letter = input("Enter a letter: ")
# Validate input (check if it's a single letter)
if len(letter) == 1 and letter.isalpha():
# Check if it's a vowel
if is_vowel(letter):
print(f"'{letter}' is a vowel.")
else:
print(f"'{letter}' is a consonant.")
else:
print("Please enter a single letter only.")
# Alternative method using string methods
# vowels = 'aeiouAEIOU'
# if letter in vowels:
# print(f"'{letter}' is a vowel.")
# else:
# print(f"'{letter}' is a consonant.")
Program Explanation:
- Function Definition: We define a function
is_vowel()
that takes a letter as parameter - Case Conversion: Convert the input to lowercase to handle both uppercase and lowercase letters
- Vowel Check: Use the
in
operator to check if the letter exists in our vowel list - Input Validation: Check if the input is exactly one character and is alphabetic
- Output: Display appropriate message based on whether the letter is a vowel or consonant
Sample Output:
Enter a letter: a
'a' is a vowel.
Enter a letter: B
'B' is a consonant.
Enter a letter: 5
Please enter a single letter only.