2

I am a beginner at python and am wondering why my code will count the characters in my string rather than the vowels?

I was trying to create a program which would count all of the vowels in my string, but it didn't work

string1 = "This is a string"
vowelCount = 0
for char in string1:
    if char in string1 == "a" or "e" or "i" or "o" or "u":
        vowelCount += 1
print(vowelCount)

The vowelCount will output as 16 instead of 4 as I intended. How would I be able to fix this issue?

  • "char in string1" will always be true this should be "if char in 'aeiou':" – CodeCupboard Dec 22 '17 at 08:12
  • That's actually a new variation of the theme. This evaluates to `if ((char in string1) and (string1 == "a")) or ("e") or ("i") or ("o") or ("u")`, which evaluates to `if (True and False) or True or True or True or True`, which evaluates to `if True`. – tobias_k Dec 22 '17 at 09:34

0 Answers0