patternpythonMinor
Counting Vowels
Viewed 0 times
countingvowelsstackoverflow
Problem
I'm learning to program and I've chosen Python as my first language. I've written a function to count vowels in a string and print the number of occurrences of each of them. Please review my code and let me know if there is a better way of writing the same as I believe there is always room for improvement.
vowels = 'aeiou'
def vowel_count(txt):
for vowel in vowels:
if vowel in txt:
print vowel, txt.count(vowel)
txt_input = raw_input('Enter text: ').lower()
vowel_count(txt_input)Solution
For a novice, your code is good. The variable names are good (though
There are ways to improve the performance a bit. I suspect that looping through the text 10 times (once for the
My real concern is if there are no vowels, then your program produces no output.
I would print the count of the vowels even if the count is 0. This shows that the code is working, and checking things. This would remove the need for the inner if-conditions too:
(and remove one scan of the text as well).
txt should be text, if I was pedantic....), and the code is logical, and well structured.There are ways to improve the performance a bit. I suspect that looping through the text 10 times (once for the
if vowel in txt, once for the txt.count(vowel), and repeated for each vowel...) is excessive. In fact, you could reduce this to just one loop through the text, but the overall saving will be quite small (for small text sizes).My real concern is if there are no vowels, then your program produces no output.
I would print the count of the vowels even if the count is 0. This shows that the code is working, and checking things. This would remove the need for the inner if-conditions too:
def vowel_count(txt):
for vowel in vowels:
print vowel, txt.count(vowel)(and remove one scan of the text as well).
Code Snippets
def vowel_count(txt):
for vowel in vowels:
print vowel, txt.count(vowel)Context
StackExchange Code Review Q#73648, answer score: 6
Revisions (0)
No revisions yet.