Practice Python Objects: Vowel Counter

Hello,
I’m stuck on a particular exercise. The question asks to print the number of vowels in a list, which I believe I did. However, I’m getting an error stating that it Is incorrect.

Can someone provide some insight?

Thanks

``````vowels = ["a", "e", "i", "o", "u"]
def vowel_counter(vowels):
for letter in vowels:
return vowels
print(len(vowels))
`````
Whats printed is 5``````

`return` inside a loop is always a good place to start. However, that is not the issue, as a whole.

When we read the name of the function we expect the function will count all the vowels in an input string, and return that count. Your function is iterating over a fixed list of vowels, then on the first iteration returning that same list.

Consider incorporating the vowels object within your function and then taking a string object as the argument.

``````def vowel_counter(string):
count = 0
for letter in string:
if letter in 'aeiouAEIOU':
count += 1
return count
``````

Now we can pass in any string, and get back what the function name suggests… A count of all the vowels.

5 Likes

Thank you very much for your help!

1 Like

why in ‘aeiouAEIOU’ ? I was only doing ‘aeiou’ and it would not pass.
So is the following True:
a != A
e != E
i != I
o != O
u != U

Yes, exactly. Lower and upper case letters have different ordinals (character code) so are not identical match. Python is case sensitive. To test for both upper and lower we need to give the full complement of vowels.

We can vary how we code, but if the SCT (the lesson checker) is looking for a pattern (all the vowels, as above) then best go with what is expected.

``````for letter in string.lower():
if letter in 'aeiou':
count += 1
``````

Above we loop over a string that is all lowercase, so only need to match lower.

``````for letter in string.upper():
if letter in 'AEIOU':
count += 1
``````

Same thing, again, only this time we only look for matches of upper case.

1 Like

This helped so much, thanks!

Is there a way to use

if letter == “A” or “a” or “E” or “e” …

or something like that rather than if letter in … ?

I’m obviously still learning but wondering why setting it equal wouldn’t work. Is it just cleaner to use in?

1 Like

You could but the `==` operator is an equivalence comparison of the two objects, you can’t check for multiple substrings because “AaEe” for example looks for that exact string. So a simple example like “you” which contains vowels will never match the string “aeiou”. So you’d need to match a lot of letters from your string with a lot of other single vowel strings, perhaps loops would help here.

For cases where you do have lots of `or` operators the any function can help but membership testing with `in` would save you a lot of effort in this case and it matches the way you’d describe what you want to achieve in English anyway. Is this letter in this other set of letters. That alone is a fairly good reason to make use of this operator.