'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):
vowels = set()
for arg in args:
for char in arg:
if char.lower() in 'aeiou':
vowels.add(char)
return len(vowels)
print(count_vowels(sys.argv[1:]))
Test Cases
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 1:[1]
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:])
Followup
To get the number of UNIQUE vowels, you should collect them all into a set, then count the length of the set.
def count_vowels(args):
vowels = set()
for arg in args:
for char in arg:
if char.lower() in 'aeiou':
vowels.add(char)
return len(vowels)
print(count_vowels(args))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
