s = "azcbobobegghakl"
count = 0
for char in s:
if char == 'a' or char== 'e' or char== 'i' or char== 'o' or char== 'u':
count += 1
print count
s = "azcbobobegghakl"
count = 0
for char in s:
if char == 'a' or 'e' or 'i' or 'o' or 'u':
count += 1
print count
Asked
Active
Viewed 23 times
0
-
2the second one always evaluates to `True` – UnholySheep Apr 23 '17 at 11:10
-
2`if char in 'aeiou'` would be more pythonic... (for the variant that works up here). – hiro protagonist Apr 23 '17 at 11:11
2 Answers
0
Non-empty strings will evaluate to True
, therefore or 'a'
will be the same as doing or True
:
>>> bool('a')
True
>>> bool('')
False
If you wanted to count the vowels, then you could use regular expressions:
import re
s = "azcbobobegghakl"
l = re.findall('[aeiou]', s)
print(len(l))
# Returns: 5

Robert Seaman
- 2,432
- 15
- 18
0
char == 'a' or 'e' or 'i' or 'o' or 'u'
will evaluate as
(((((char == 'a') or 'e') or 'i') or 'o') or 'u')
. Since any string other than the empty string will evaluate to True
, your expression is the same as evaluating char == 'a' or True
, which will be always True
.

Thiago Barcala
- 6,463
- 2
- 20
- 23