Python 3 Exception: TypeError: function missing 1 required positional argument: 'words'

大兔子大兔子 提交于 2020-01-24 13:43:45

问题


My function needs one argument words, but i want the program not to crash if no argument.

def get_count(words):
    try:
        consonants_str = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
        vowels_str = "aeiouAEIOU"
        consonants_ls = []
        vowels_ls = []
        words_ls = []
        result = {"vowels": 0, "consonants": 0}`

        for element in consonants_str:
            consonants_ls.append(element)

        for element in vowels_str:
            vowels_ls.append(element)

        if type(words) != type(None):
            for element in words:
                words_ls.append(element)

            for element in words_ls:
                if element in vowels_ls:
                    result["vowels"] += 1
                if element in consonants_ls:
                    result["consonants"] += 1
                else:
                    continue
            else:
                result["vowels"] = 0
                result["consonants"] = 0

    except TypeError:
        result["vowels"] = 0
        result["consonants"] = 0

    answer = {"vowels": result["vowels"],"consonants": result["consonants"]}

    return answer`

So if I execute the function with

print(get_count())

I want, that the program doesn't show me an error like the one in the heading. The exception for that should be in the def of get_count because it should be a closed file. I don't execute in the same file, so the Exception should be independent from other files.

I hope you understand what I mean...

Thanks for your answers! NoAbL


回答1:


You're not passing an argument to your function, when you declared that you want an argument named words with def(words), call your function like this or with any string input you desire

print(get_count('AAAABBBKDKDKDKDA'))

if you want the program to exit when no argument is passed, do this (remember words is now a tuple)

import sys

def get_count(*words):
    if not words: # if words is empty, no argument was passed
        sys.exit('You passed in no arguments')
    else:
        pass # do something with the items in words



回答2:


You can use Optional parameters

For example:

def info(name, age=10):

is a function with optional parameter age.

The valid calls of info are:

info("Roy")
info("Roy", 15)

In your case you can just change your function to this:

def get_count(words=[]): # Assuming words is a list. If it is a string you can use words=""

So, if you don't pass any arguments, by default the function takes words as an empty list.

Bonus:

I've found

for element in consonants_str:
    consonants_ls.append(element)

for element in vowels_str:
    vowels_ls.append(element)

You don't need this. Instead you can do this:

consonants_ls = list(consonants_str)
vowels_ls = list(vowels_str)



回答3:


Pythonic way:

>>> vowels = 'aeiou'
>>> def get_count(words):
...     words = words.lower()
...     total_vowels = sum(words.count(x) for x in vowels)
...     return {'vowels':total_vowels, 'consonants':len(words)-total_vowels}
... 
>>> get_count('AAAABBBKDKDKDKDA')
{'consonants': 11, 'vowels': 5}

Using collections.Counter:

>>> def get_count(words):
...     words = words.lower()
...     my_counter = collections.Counter(words)
...     total_vowels = sum(my_counter.get(x,0) for x in 'aeiou')
...     return {'vowels':total_vowels, 'consonants':len(words)-total_vowels}
... 
>>> get_count('AAAABBBKDKDKDKDA')
{'consonants': 11, 'vowels': 5}


来源:https://stackoverflow.com/questions/35968844/python-3-exception-typeerror-function-missing-1-required-positional-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!