Skip to content

script_13.py - Vowel or Consonant Checker

Code

Python
#!/usr/bin/env python3
"""Vowel or consonant checker"""

letter = input("Enter a letter: ").lower()

if len(letter) == 1 and letter.isalpha():
    if letter in "aeiou":
        print(f"{letter} is a vowel")
    else:
        print(f"{letter} is a consonant")
else:
    print("Please enter a single letter")

Explanation

Line 4: letter = input("Enter a letter: ").lower() - input() returns string type (str) - .lower() is a string method that returns a new lowercase string - Method chaining: input() result is immediately used to call .lower() - letter stores the lowercase string - Makes comparison case-insensitive ("A" becomes "a")

Line 6: if len(letter) == 1 and letter.isalpha(): - len() returns integer representing string length - == 1 checks if exactly one character was entered - and requires BOTH conditions to be True - .isalpha() is a string method that returns boolean - Returns True if all characters are alphabetic (a-z, A-Z) - Returns False for numbers, symbols, spaces - Validates input before checking vowel/consonant

Line 7: if letter in "aeiou": - Nested if statement (inside the first if block) - in is membership operator for strings/sequences - Checks if letter appears anywhere in the string "aeiou" - Returns boolean (True if found, False otherwise) - "aeiou" is a string literal containing all vowels

Line 9: else: (inner) - Corresponds to the inner if (line 7) - Letter is alphabetic and single, but not a vowel - Therefore must be a consonant

Line 11: else: (outer) - Corresponds to the outer if (line 6) - Input was either multiple characters or not alphabetic