Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Consonants

Count consonants with a character loop. Students require a letter before excluding vowels and see the English-vowel rule applied to Unicode alphabetic text.

BeginnerPhase 5 - Category 1: Basic String HandlingExample 6 of 10
count-consonants.py
1# Take string input
2s = input("Enter a string: ")
3
4# Count consonants
5vowels = "aeiouAEIOU"
6count = 0
7for char in s:
8 if char.isalpha() and char not in vowels:
9 count += 1
10
11print(f"Number of consonants: {count}")

Output

Enter a string: Hello
Number of consonants: 3

In this one

  • Filter alphabetic nonvowels
  • Exclude punctuation
  • Understand the chosen vowel set

How it works

  1. 1

    Visit each character.

  2. 2

    Require isalpha and absence from vowels.

  3. 3

    Increment the consonant count for each match.

Edge cases

Do spaces count as consonants?

Do spaces count as consonants?

No. They fail isalpha.

Does uppercase B count?

Does uppercase B count?

Yes. It is alphabetic and not in the vowel list.

What's going on

The condition combines char.isalpha() with char not in vowels. That prevents digits and punctuation from being counted merely because they are not vowels.

Every qualifying letter adds one to count. Both English cases are covered by the vowel string. isalpha recognizes more than English letters, so alphabetic characters outside that vowel list fall into this program's consonant category even when linguistically imperfect.

Do spaces count as consonants? No. They fail isalpha.

Does uppercase B count? Yes. It is alphabetic and not in the vowel list.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why include isalpha?

Pick an answer to check it.

Question 2

Do spaces count as consonants?

Pick an answer to check it.

Questions people ask

Do spaces count as consonants?

No. They fail isalpha.

Does uppercase B count?

Yes. It is alphabetic and not in the vowel list.

Why include isalpha?

Nonvowels are not necessarily letters.