0
def counter(sentence):
a=0
e=0
i=0
o=0
u=0
for char in sentence:
    if char == 'a' or 'A':
        a += 1
    elif char == 'e' or 'E':
        e += 1
    elif char == 'i' or 'I':
        i += 1
    elif char == 'o' or 'O':
        o += 1
    elif char == 'u' or 'U':
        u += 1
return a, e, i, o, u

Everything looks okay to me, but when I print counter("Hello how is your day going") it returns (27, 0, 0, 0, 0). 27 is the total number of characters in that sentence so it's clear that for every character the for loop goes over, it stops after the first if condition and adds 1 to a, but I don't know why.

Also, messed up the indentation after the function definition, don't know how to fix it, obviously it's not like that in the program.

durron597
  • 31,968
  • 17
  • 99
  • 158
conjenks
  • 409
  • 1
  • 6
  • 18

3 Answers3

2

When the if statement is evaluated, it evaluates as being char == 'a' and 'A'. Since 'A' is a boolean True, the or operator is triggered, and the if statement happens. Essentially, the if statement is translated as this:

(char == 'a') or 'A'

Demonstration

>>> char == 'a'
False
>>> 'A'
True
>>> True or False
True
bcdan
  • 1,438
  • 1
  • 12
  • 25
  • Ah, okay, I see. The Python interpreter was reading it as `if (char == 'a') or 'A'`, and a string always evaluates to true. Thanks. – conjenks May 27 '15 at 00:38
1

Here is a little hint!

if char == "a" or char == "A":
    a += 1 

etc.

ncmathsadist
  • 4,684
  • 3
  • 29
  • 45
1

This is one way to do it:

v = ['a', 'e', 'i', 'o', 'u',]
s = list("Hello World")
x = [i for i in v if i in s]
print x
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48