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

Time:07-25

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")

CodePudding user response:

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

CodePudding user response:

Your code is fundamentally flawed in that it is using try-except to run a function that will not give out errors until and unless the argument passed to the function is of non-string type(int, list, etc.) i.e even if the input is 11aa2b, the function will simply get executed without throwing any errors.

Try something like this instead:

def string_processor(string):
    countA = 0
    assert(string.isalpha())
    for c in string:
        if c=='a' or c=='A':
            countA  = 1
    return countA

try:
    print(string_processor('abA'))
except:
    print('Please enter a string.')
  • Related