-2

I've literally just started learning to code so very inexperienced, and I probably haven't done this the best way - I'm trying to write code in Python that will count the number of DIFFERENT vowels in a string (i.e. if the input was 'Hello my name is Simon' the output should be '4' as the string contains a, e, i and o)

a="a"
A="A"
e="e"
E="E"
i="i"
I="I"
o="o"
O="O"
u="u"
U="U"
num_of_diff_vowels=0
print("This program will count the number of vowels in your string")
ans = input("Enter string here:")
if a or A in ans:
    num_of_diff_vowels=num_of_diff_vowels+1
if e or E in ans:
    num_of_diff_vowels=num_of_diff_vowels+1
if o or O in ans:
    num_of_diff_vowels=num_of_diff_vowels+1
if i or I in ans:
    num_of_diff_vowels=num_of_diff_vowels+1
if u or U in ans:
    num_of_diff_vowels=num_of_diff_vowels+1

print(num_of_diff_vowels)

So far with this code all I'm getting in the output is '5'... Any ideas of how to refine this and actually make it work?

  • Hint: `if x or y in ans` does not do what you think. – Arnav Borborah Oct 25 '18 at 17:07
  • 1
    And an easier way would be to make all the text lowercase, place the characters in a set, filter out non-vowels, then check the size of the set. – Carcigenicate Oct 25 '18 at 17:08
  • On another note, you don't even need all of those variables for the vowels. And to avoid comparing against upper and lowercase values, I would convert the input string to one or the other. – Arnav Borborah Oct 25 '18 at 17:09
  • 1
    `len([e for e in list('aeiou') if e in ans.lower()])` does what you want in one line. – Rocky Li Oct 25 '18 at 17:10

1 Answers1

0

All you if's are always true because they don't do what you think they do. You must change them to

if a in ans or A in ans

and so on.

Psytho
  • 3,313
  • 2
  • 19
  • 27