Question 7
Back to Exercise
Count the vowels, consonants, digits and spaces in a sentence with a single loop.
Solution
text = "LearnFrenzy has 25 Python topics"
vowels = consonants = digits = spaces = 0
for ch in text:
if ch.lower() in "aeiou":
vowels += 1
elif ch.isalpha():
consonants += 1
elif ch.isdigit():
digits += 1
elif ch == " ":
spaces += 1
print(f"vowels={vowels} consonants={consonants} digits={digits} spaces={spaces}")
vowels=7 consonants=19 digits=2 spaces=4
The vowel test comes first; every other letter is a consonant. ch is one character, so in "aeiou" is a safe single-letter test here.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!