Test Index

Python Revision Tour Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 12 of 102
Marks: +1, -0
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)
[CBSE 2026 Set 4]
Solution:  
Errors found:
1. range(s): range() needs an integer, not a string (TypeError). Loop directly over the string: for ch in s:
2. 'aeiouAEIOU' in ch checks whether the whole vowel string is inside one character, which is always False. It must be ch in 'aeiouAEIOU'.
3. c=+1 assigns +1 to c every time instead of adding 1. It must be c+=1 (or c=c+1).
4. return(ch) returns the last character; the count is in c, so it must be return(c).
Corrected code (corrections underlined):
def CountVowels(s):
c=0
for ch in s:
if ch in 'aeiouAEIOU':
c+=1
return(c)
Check: CountVowels("Computer Science") returns 6 (o, u, e, i, e, e).
© examsnet.com
Advertisements
Go to Question: