Linda Acquaviva Linda Acquaviva - 1 month ago 10
Python Question

Vowel checker always returns zero instead of vowel count

This program is a vowel checker that accepts arguments from the commandline, but its not working properly. Why does the count always return 0? What is wrong here?

import sys

string = sys.argv[1:]

def is_vowel(c):
vowel = (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u' or c == 'y')
return vowel



def count_vowels(string):
count = 0
for v in string:
if is_vowel(v) == True:
count += 1
return count

print(count_vowels(string))


EDIT: I have found that the program works when I change string = sys.argv[1:] to string = sys.argv[1]

Can someone explain why this is happening?

Answer Source

string is a list because you are setting it to sys.argv[1:] which is a slice of argv. So when you iterate over string, you are actually iterating over its elements and not an actual str.

If you want to do multiple inputs, you can try:

for i in sys.argv[1:]:
  print(count_vowels(i))