1

So I am new to coding (and StackOverflow) and practicing on CodeWars. I have wrote this for loop to count vowels, but when doing the sample test, I am receiving an output I do not understand.

def getCount(inputStr):
    num_vowels = 0
    # your code here
    for i in inputStr:
        if i == 'a' or 'e' or 'i' or 'o' or 'u' or 'A' or 'E' or 'I' or 'O' or 'U':
            num_vowels += 1
            print(num_vowels)
    
    return num_vowels

I get an output of 11 instead of 5 when running the test case "abracadabra". I wanted to understand the reasoning behind getting 11 instead of 5.

def getCount(inputStr):
    num_vowels = 0
    # your code here
    for i in inputStr:
        if i == 'a':
            num_vowels += 1
            print(num_vowels)
    
    return num_vowels

Running the code above would allow me to succeed in my sample test but obviously would fail in the test cases. Also is there any way to optimize my code because writing out every single vowel and adding or seems to be wrong. Thanks for the help!

Working Code Not working Code

Jim108
  • 11
  • 1
  • 2
    should be `if i == 'a' or i == 'e' or i == .. :` or `if i in ['a', 'e', ...]:` or `if i in "ae...":` – furas Feb 16 '20 at 15:20

0 Answers0