Reputation: 35
I am a beginner and my objective is this - Write a function called count_vowels that accepts a string argument that represents a word and returns the number of vowels that are in the word.
Heres my code so far to explain:
string = 'oboe'
def count_vowels(string):
count = 0
if 'a' or 'A' in string:
count += 1
if 'e' or 'E' in string:
count += 1
if 'i' or 'I' in string:
count += 1
if 'o' or 'O' in string:
count += 1
if 'u' or 'U' in string:
count += 1
return count
print(count_vowels(string))
Where i am a bit lost is the output value. If you run this code with the word 'oboe' you get 5. makes no sense So i was wondering, do elif statements change the output? Besides that, what would I need to alter in my code to have it work properly. I feel like something is being iterated upon too many times.
thank you!
Upvotes: 1
Views: 703
Reputation: 195508
The if-conditions in form if 'a' or 'A' in string:
etc. are always evaluating to True
. It should be if ('a' in string) or ('A' in string):
.
Also, it's necessary to evaluate these conditions in a loop, to get correct answer.
Here is example with sum()
builtin:
def count_vowels(string):
return sum(ch in 'aeiou' for ch in string.lower())
print(count_vowels('oboe'))
Prints:
3
Upvotes: 3