LearnFrenzy
Sign in Take a free test

Loops · Loops Coding Problems · Question 7

Count vowels, consonants, digits and spaces in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Count the vowels, consonants, digits and spaces in a sentence with a single loop.

Solution
main.py Run
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}")

Output Verified by running it on Python 3

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links