Question:

The function given below is written to accept a string s as a parameter and return the number of vowels appearing in the string. The code has certain errors. Observe the code carefully and rewrite it after removing all the logical and syntax errors. Underline all the corrections made.

def CountVowels(s):
    c=0
    for ch in range(s):
        if 'aeiouAEIOU' in ch:
            c=+1
    return(ch)

Show Hint

There are four mistakes: range(s), the swapped in test, c=+1 and return(ch). Fix each one.
Updated On: Oct 20, 2026
Show Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Read the intended job:
The function must count the vowels in the string s and return that count.
We go through each character of s, test if it is a vowel, and add 1 to the counter c.

Step 2: Find the errors line by line:
Error 1: for ch in range(s). The function range() needs an integer, but s is a string. Running range('abc') gives a TypeError. The loop must go over the string itself: for ch in s.
Error 2: if 'aeiouAEIOU' in ch. This asks if the whole vowel string is inside the single character ch, which is almost always False. We must ask if ch is inside the vowel string: if ch in 'aeiouAEIOU'.
Error 3: c=+1. This only sets c to +1 each time, so the count never grows. The correct form is c+=1.
Error 4: return(ch). This returns the last character, not the count. It must be return(c).

Step 3: Write the corrected code:
The corrected parts are underlined.
def CountVowels(s):
    c=0
    for ch in s:
        if ch in 'aeiouAEIOU':
            c+=1
    return(c)

Step 4: Test the corrected function:
CountVowels('Education') checks E, d, u, c, a, t, i, o, n. The vowels are E, u, a, i, o, so it returns 5.

Final Answer:
Corrected code:
def CountVowels(s):
    c=0
    for ch in s:
        if ch in 'aeiouAEIOU':
            c+=1
    return(c)

Four corrections: range(s) to s, the reversed in test, c=+1 to c+=1, and return(ch) to return(c).
Was this answer helpful?
0
0