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

How do I get my main function to work while exceptions check the inputted variable?

I managed to get my except functions working but that makes my main function not be able to work for some reason. I would really like to get my main function to work as it supposed to only accept letters and exception handle some possible errors encountered when inputting into the function.

def string_processor(string):  
    
    #The main function, 
    countA = 0
    if (string.isalpha()):
        for c in string:
            if c == "a":
                countA = countA + 1
            return (countA / len(string))
    
#finds any errors in the variable placed into the code
try:
    string_processor("aaaa")
except AttributeError:
    print("Please enter a string instead.")
except TypeError:
    print("Please input only 1 string.")
except NameError:
    print("This is not a string, please input a string")
else:
    print("String contained non-letters or unknown error occured")


For some reason, this code below is able to get the main function to work, but at the cost of only able to get Attribute errors and not the other specific errors such as TypeError and NameError.

def string_processor(string):  
    
    try:
        countA = 0
        if (string.isalpha()):
            for c in string:
                if c == "a":
                    countA = countA + 1
            return countA / len(string) 

#Exceptions
    except AttributeError:
        print("Please enter a string instead.")
    except TypeError:
        print("Please input only 1 string.")
    else:
        print("string contains non-letters or unknown error occured")
        
string_processor("1,","1")

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

>Solution :

The problem is that the else statement will be executed when the code have no exception.

Try to replace

else:
    print("string contains non-letters or unknown error occured")

to:

except Exception:
    print("String contained non-letters or unknown error occured")

or even better:

except Exception as e:
    print(e)

In this way, if you get an unexpected exception the program will print it

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