简体   繁体   中英

Exception handling in python Counting the number of characters in a string

This is my code.

def word_count(my_string):
    count=1
    if type(my_string) == str:
        try:
            for eachCharacter in my_string:
                if eachCharacter==' ':
                    count+=1
            return count
        except:
            return "Not a string"

i have to get output as:

Word Count: 4
Word Count: 1
Word Count: 7
Word Count: Not a string
Word Count: Not a string
Word Count: Not a string

but i'm getting:

Word Count: 4
Word Count: 1
Word Count: 7
Word Count: None
Word Count: None
Word Count: None

Can anyone help me in finding this error

Изучите enumerate([1, 2, ...]) и raise Exeption("...")

You need to handle the case where the input is not a string:

def word_count(my_string):
    count=1
    if type(my_string) == str:
        for eachCharacter in my_string:
            if eachCharacter==' ':
                count+=1
        return count
    return "Not a string"

As you have it now, your function doesn't explicitly return anything, and therefore returns None , if the passed in object is not a string. Also, the try/except does you no good since the code inside the try will never throw an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM