A programmer wrote this code to count vowels and consonants. It contains…
2026
A programmer wrote this code to count vowels and consonants. It contains subtle bugs.
text = input()
vowels = consonants = 0
i = 0
while i <= len(text) ;
ch = text[i]
if ch.lower in 'aeiou':
vowels += 1
elif ch.isalpha():
consonants — 1
i += 2
print(f'Vowels: {vowels}, Consonants: {consonants}')
(i) Identify every bug. For each, state the line, nature of error — syntax/runtime/logical — and its effect.
(ii) Write a corrected version of the program that counts vowels, consonants, digits and spaces using a single while loop.
(iii) Rewrite the program using a for loop and dictionary. Demonstrate that both versions give same output for 'Hello World 2026'.
(iv) Explain short-circuit evaluation and show how it can simplify the conditional to a single compound condition without elif.
Show answer & explanation
(i) Bugs in the Given Program
Line | Bug | Type of Error | Effect |
|---|---|---|---|
|
| Syntax Error | Program will not run |
| Condition should be | Runtime Error | Index out of range when |
|
| Logical Error | Method object compared instead of character |
| Wrong operator used | Syntax Error | Invalid statement |
| Should be | Logical Error | Consonants not counted |
| Increment only in one block | Logical Error | Infinite loop possible |
Missing increment for all cases |
| Logical Error | Loop may never terminate |
(ii) Correct Program using Single While Loop
text = input("Enter text: ")
vowels = consonants = digits = spaces = 0
i = 0
while i < len(text):
ch = text[i]
if ch.lower() in "aeiou":
vowels += 1
elif ch.isalpha():
consonants += 1
elif ch.isdigit():
digits += 1
elif ch.isspace():
spaces += 1
i += 1
print("Vowels:", vowels)
print("Consonants:", consonants)
print("Digits:", digits)
print("Spaces:", spaces)(iii) Program using For Loop and Dictionary
text = "Hello World 2026"
count = {
"vowels": 0,
"consonants": 0,
"digits": 0,
"spaces": 0
}
for ch in text:
if ch.lower() in "aeiou":
count["vowels"] += 1
elif ch.isalpha():
count["consonants"] += 1
elif ch.isdigit():
count["digits"] += 1
elif ch.isspace():
count["spaces"] += 1
print(count)Output for "Hello World 2026"
Vowels: 3
Consonants: 7
Digits: 4
Spaces: 2Both programs produce the same output.
(iv) Short-Circuit Evaluation
Short-circuit evaluation means Python stops checking conditions once the final result is known.
Example:
if ch.isalpha() and ch.lower() in "aeiou":If ch.isalpha() is False, Python will not check the second condition.
This can simplify conditions without using elif.
Example:
if ch.isalpha() and ch.lower() in "aeiou":
vowels += 1
if ch.isalpha() and ch.lower() not in "aeiou":
consonants += 1A video solution is available for this question — log in and enroll to watch it.