-2

I have an assignment about strings in loop and I need to find out how many (a,e,i,o,u) in the input . I have done it but I think it's too long. I want to make it shorter but I have no idea how.

This is my code:

x=input("enter the taxt that you need me to count how many (a,e,i,o,u) in it:")

a=len(x)

x1=0

x2=0

x3=0

x4=0

x5=0

for i in range(a):
    h=ord(x[i])

    if h == 105:
        x1+=1
    elif h == 111: 
        x2+=1
    elif h == 97:
        x3+=1
    elif h == 117:
        x4+=1
    elif h == 101:
        x5+=1

print("There were",x3,"'a's")
print("There were",x5,"'e's")
print("There were",x1,"'i's")
print("There were",x2,"'o's")
print("There were",x4,"'u's")
deceze
  • 510,633
  • 85
  • 743
  • 889
abdulraman
  • 65
  • 5

3 Answers3

1

You can just define your list of characters you care about (vowels) in a string, then use dictionary comprehension. This code will print out what you want and also leave you with all of the values stored in a dictionary called vowel_count:

vowels = 'aeiou'

x=input("enter the taxt that you need me to count how many (a,e,i,o,u) in it:")

vowel_count = {vowel: x.count(vowel) for vowel in vowels}

for vowel in vowels:
    print("There were ",vowel_count[vowel]," '", vowel, " 's")
Community
  • 1
  • 1
Kewl
  • 3,327
  • 5
  • 26
  • 45
0

Instead of 5 variables for counting and 5 constant for comparing use the dictionary:

h = {105: 0, 111: 0, 97: 0, 117: 0, 101: 0}

or - nicer -

h = {'i': 0, 'o': 0, 'a': 0, 'u': 0, 'e': 0}

so your full code will be

x = input("Enter the text that you need me to count how many (a,e,i,o,u) in it: ")
h = {'i': 0, 'o': 0, 'a': 0, 'u': 0, 'e': 0}

for i in x:              # there is no need to index characters in the string
    if i in h:
      h[i] += 1

for char in h: 
    print("There were {} '{}'s".format(h[char], char))  
MarianD
  • 13,096
  • 12
  • 42
  • 54
0

Simple approach according to this question:

x = input("Enter the text that you need me to count how many (a,e,i,o,u) are in it:")

print("There were", x.count('a'), "'a's")
print("There were", x.count('e'), "'e's")
print("There were", x.count('i'), "'i's")
print("There were", x.count('o'), "'o's")
print("There were", x.count('u'), "'u's")
Community
  • 1
  • 1
Michael H.
  • 3,323
  • 2
  • 23
  • 31