π Day 65/150 – Count Consonants in a String in Python
Consonants are all alphabet characters except vowels (a, e, i, o, u).
In Python, we can count consonants using loops, conditions, list comprehensions, and functions.
Let’s explore different methods π
πΉ Method 1 – Using for Loop
✅ Output
Consonant Count: 13
π Checks whether the character is an alphabet and not a vowel.
πΉ Method 2 – Taking User Input
text = input("Enter a string: ") count = 0 for ch in text.lower(): if ch.isalpha() and ch not in "aeiou": count += 1 print("Consonant Count:", count)
π Allows users to enter any string dynamically.
πΉ Method 3 – Using List Comprehension
✅ Output
Consonant Count: 13
π Cleaner and shorter Pythonic approach.
πΉ Method 4 – Using Function
✅ Output
13
π Best method for reusable programs.
Key Takeaways
✅ isalpha() ignores spaces and symbols
✅ not in "aeiou" helps identify consonants
✅ List comprehensions make code compact
✅ Functions improve code reusability


0 Comments:
Post a Comment