0

I a very new to Python and I am having a hard time understanding why the following code does not work as intended. The idea is for the code to count the vowels in a string, I can get this to work in a different, way but I would like to understand why the following does not work:

s = "tester"
vowelCount = 0

for letters in s:
     if letters == "a" or "e" or "i" or "o" or"u":
         vowelCount += 1

print("Number of vowels: " + str(vowelCount))

Output: Number of vowels: 6

I've put this throug http://pythontutor.com/ to step through but I am none the wiser. I've had a look into 'Lazy evaluation' but I don't see how this applies to the above code.

PyMerr
  • 1
  • 1
  • You have 5 different expressions evaluated in Boolean contexts, joined into a single expression by 4 uses of `or`. The closest equivalent of what you want would be `any(letter == x for x in "aeiou")`. `==` and `or` do not "work together" in the way you think they do based on how English works. – chepner Jun 06 '21 at 18:42

1 Answers1

0

The or operator evaluates each statement separately. All of the individual letters "e" "i" etc. evaluate as true.

To do what you want would be:

for letters in s:
     if letters == "a" or letters == "e" or letters == "i":
         vowelCount += 1

A perhaps better approach would be:

for letters in s:
    if letters in ['a', 'e', 'i', 'o', 'u']:
         vowelCount += 1
William
  • 381
  • 1
  • 8
  • You can compact the second option a bit further with: if letters in "aeiou" – Seon Jun 06 '21 at 18:45
  • @Seon Certainly true, and that's what I would do for the vowel question. Though since this is a learning exercise I think it's good to show the approach with lists which is more extensible to other questions. – William Jun 06 '21 at 18:47