Reputation: 11
I am trying to solve this problem below
Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print:
Number of vowels: 5
I wrote the following code
s='azcbobobegghakl'
count = 0
for vowels in s:
if vowels in 'aeiou':
count += 1
print ('Number of vowels: ' + str(count))
This was not correct. I learned that you should not define "azcbobobegghakl" as s or g or anything else for that matter. Do I need to use a certain function to accomplish this?
Upvotes: 1
Views: 225
Reputation: 11
s = str(input("Enter a phrase: "))
count = 0
for vowel in s:
if vowel in 'aeiou':
count += 1
print("Number of vowels: " + str(count))
This seems to work on python but it is not the right answer.
Upvotes: 0
Reputation: 33714
You can use a list comprehension and then count the list.
print("Number of vowels: {}".format(len([vowel for vowel in input() if vowel in "aeiou"])))
The question is asking to count the number of vowels in any string, not just the example azcbobobegghakl
, therefore you should replace the fixed string with an input()
.
Upvotes: 2
Reputation: 4536
What you have seems to do the task required by the question, however, if the do want it in the form of a function you can restate the code you already have as a function:
def count_vowels(s):
count = 0
for vowels in s:
if vowels in 'aeiou':
count += 1
print ('Number of vowels: ' + str(count))
Then, you can execute your program with the following:
count_vowels('azcbobobegghakl')
Upvotes: 1