Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NameError: name 'args' is not defined when trying to print out the number of vowels in a string

Create a program called countVowels.py that has a function that takes in a string then prints the number of unique vowels in the string (regardless of it being upper or lower case).

countVowels.py

import sys

def count_vowels(args):
    args = sys.argv[1:]
    count = 0 

    for arg in args:
        for char in arg:
            if char.lower() in ['a', 'e', 'i', 'o', 'u']:
                count += 1 

    print("{}".format(' ', count))

count_vowels(args)

Test Cases

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

python3 countVowels.py Data
python3 countVowels.py 'Python Python'
python3 countVowels.py 'eiOuayOI j_#Ra'

The following is the error message displayed:

Traceback (most recent call last):
  File "countVowels.py", line 14, in <module>
    count_vowels(args)
NameError: name 'args' is not defined

>Solution :

Right, because it’s not defined. You need to pass the sys.argv subset to the function. Right now, you are throwing away the parameter args by overwriting it.

What you should do is delete the sys.argv reference in the function:

def count_vowels(args):
    count = 0 
...

And change the main to:

count_vowels(sys.argv[1:])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading