Rob Bibb
Rob Bibb

Reputation: 39

My program for counting how many vowels in a user input sentence doesn't count the same vowel twice. How do i fix this?

print ("Sentence analysis")

Sentence = (input("Please enter a sentence"))


def WordCount(Sentence):
    words = (Sentence.count(' ')+1)
    print ("There are", words ,"words in this sentence")
WordCount(Sentence)

The code above is fine and used to count how many words in the input sentence.

vowels = ['a','e','i','o','u']
count=0
for v in vowels:
    if v in Sentence:
        count+=1


print (count)

When running, say if I input a a e i o u would only count 5 vowels whereas there are 6. How do I fix this?

Upvotes: 0

Views: 70

Answers (4)

yhlleo
yhlleo

Reputation: 13

For the first code can be simplified the WordCount() function as:

print(len(Sentence.split()))

or:

import re
print(len(re.findall(r'\w+', Sentence)))

Upvotes: 0

idjaw
idjaw

Reputation: 26580

That is because you are doing your check in reverse. You want to go over your sentence and check each letter against vowels:

vowels = ['a','e','i','o','u']
count=0
for s in Sentence:
    if s in vowels:
        count+=1


print (count)

For a nicer approach, however, check out @zondo's answer.

Upvotes: 1

Mark Skelton
Mark Skelton

Reputation: 3891

The problem you are having is that when you loop through v in vowels and check if v is in Sentence it only checks if it v is present in Sentance not how many times. If you flip it around so it checks through Sentence first and check each letter to see if it is in vowels it will check all of the letters in Sentence.

print ("Sentence analysis")

Sentence = (input("Please enter a sentence"))

vowels = ['a','e','i','o','u']
count=0
for letter in Sentence:
    if letter in vowels:
        count+=1

print (count)

Upvotes: 0

zondo
zondo

Reputation: 20346

Use .count():

count = 0
for v in vowels:
    count += Sentence.count(v)

Or better:

count = sum(Sentence.count(v) for v in vowels)

Upvotes: 4

Related Questions