Home > Software design >  How can I add exception handling without skiping into the next input function?
How can I add exception handling without skiping into the next input function?

Time:12-03

valid_Total = 120

def get_num(n):
    inp = -1
    while input not in range(121):
        try:
            inp = int(input(f"Enter your total {n} credits : "))
            if inp not in range(121):
                print("Out of range")
            else:
                pass
        except ValueError:
            print("Please enter a integer")
        return inp


while True:
    x = get_num("PASS")
    y = get_num("DEFER")
    z = get_num("FAIL")
    if x y z != valid_Total:
        print("Incorrect Total")
    else:
        break

How can I fix the exception handling so when I input anything other than a integer it ask to enter the value again to the same variable without procceeding it onto the next variable?

CodePudding user response:

You can simplify this with a "infinite" loop

def get_num(n):
    while True:
        inp = input(f"Enter your total {n} credits : ")
        try:
            inp = int(inp)
            if inp in range(121):
                return inp
            print("Out of range")
        except ValueError:
            print("Please enter an integer")

The only way out of the loop is to reach the return statement, by both avoiding a ValueError and successfully passing the range check.

If you don't want to nest the range check inside the try statement (a reasonable request), you can use a continue statement to skip the range check in the event of an exception.

def get_num(n):
    while True:
        inp = input(f"Enter your total {n} credits : ")

        try:
            inp = int(inp)
        except ValueError:
            print("Please enter an integer")
            continue

        if inp in range(121):
            return inp

        print("Out of range")

You can also invert the range check by using an additional continue statement.

def get_num(n):
    while True:
        inp = input(f"Enter your total {n} credits : ")

        try:
            inp = int(inp)
        except ValueError:
            print("Please enter an integer")
            continue

        if inp not in range(121):
            print("Out of range")
            continue

        return inp

CodePudding user response:

Simply add continue at the end of your except clause:

        except ValueError:
            print("Please enter a integer")
            continue

It will go back to the top of the while

  • Related