2

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
  • 1
    It works now. I'm sorry that i can't give the green hook to 2 people, so i gave it to the one who answered first and helped me a lot. That doesn't mean the other answers are less good. Commented Mar 13, 2016 at 11:05

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

5 Comments

I know, i want an escape sequence or something like that if i don't pass an argument.
use def get_count(*args) args is a tuple and enables you to pass no argument at all or pass in any number of non-named arguments
you can use any name like *optional but *args is what is used by the community, personally i've never seen any standard code that uses a different name. but it's important that you know about the freedom that python allows in that area
If i change the def get_count(words) to def get_count(*words), the output is always {"consonants": 0, "vowels": 0}
because words is no longer a string it's now a tuple containing strings, so it should be for element in words[0] that's if you care about only the first string passed (multiple strings can be passed in to the function)
1

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)

Comments

1

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.