English

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 - Computer Science (Python)

Advertisements
Advertisements

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)
Code Writing
Advertisements

Solution

def CountVowels(s):
    c = 0
    for ch in s:
        if ch in 'aeiouAEIOU':
            c += 1
    return c
  1. Loop Correction: Changed range(s) to s to iterate through each character of the string.
  2. Membership Logic: Changed 'aeiouAEIOU' in ch to ch in 'aeiouAEIOU' to check if the character is a vowel.
  3. Increment Correction: Changed c=+1 (which just assigns 1) to c += 1 to properly increment the counter.
  4. Return Correction: Changed return(ch) to return c to return the final count instead of the last character.
shaalaa.com
  Is there an error in this question or solution?
2025-2026 (March) Set 4
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×