TempTask
TempTask

Reputation: 31

Is there a way to shorten multiple if statements?

This is a program to count all the vowels in a word, the majority of the program is multiple if statements, is there any way I could shorten this?

word = input("enter a word ").lower()
a, e, i , o , u = 0, 0, 0, 0, 0
letters = [char for char in word]
for x in range(0,len(letters)):
    if letters[x] == "a":
        a += 1
    elif letters[x] == "e":
        e += 1
    elif letters[x] == "i":
        i += 1
    elif letters[x] == "o":
        o += 1
    elif  letters[x] == "u":
        u += 1
print(f"The word `{word}` has {a} `a` characters, {e} `e` characters, {i} `i` characters, {o} `o` characters, {u} `u` characters")

Upvotes: 2

Views: 623

Answers (1)

chepner
chepner

Reputation: 530843

Don't use 5 separate variables, one per vowel. Use a single dict with vowel keys.

vowels = "aeiou"
vowel_counts = { x: 0 for x in vowels }

for x in letters:
    if x in vowels:
        vowel_counts[x] += 1

print(f"The word `{word}` has {vowel_counts['a']} `a` characters, {vowel_counts['e']} `e` characters, {vowel_counts['i']} `i` characters, {vowel_counts['o']} `o` characters, {vowel_counts['u']} `u` characters")

Upvotes: 7

Related Questions