0

this function goal is to count the vowels but the if statement is being executed in all the cases this is the code:

def count_vowels(txt):
  count=0
  txt = txt.lower()
  for char in txt:
    
    if char == "a" or "e" or "i" or "o" or "u":
       count = count+1
    
  print(count)

count_vowels(mark)

it has to print 1 but it's printing 4

Harben
  • 1,802
  • 1
  • 11
  • 16

1 Answers1

1

The issue is that you are comparing char to 'a' and then just checking string values if they exists which is a value and will always be truthy in this case.

def count_vowels(txt):
  count=0
  txt = txt.lower()
  for char in txt:
    
    if char == "a" or "e" or "i" or "o" or "u":
       count = count+1
    
  print(count)

count_vowels(mark)

You would need to do:

def count_vowels(txt):
  count=0
  txt = txt.lower()
  for char in txt:
    
    if char == "a" or char == "e" or char == "i" or char == "o" or char == "u":
       count = count+1
    
  print(count)

count_vowels(mark)

Or a cleaner alternative:

def count_vowels(txt):
  count=0
  txt = txt.lower()
  for char in txt:
    
    if char in ['a', 'e', 'i', 'o', 'u']:
       count = count+1
    
  print(count)

count_vowels(mark)
Harben
  • 1,802
  • 1
  • 11
  • 16