How do I move back to try block after catching exception

Viewed 261

How do I move back to my try block after catching the exception? Below is the code:

def main():

    while True:
        try:
            a = int(input("Enter first value"))

        except ValueError:
            print("Please enter a number")
            main()
        try:
            b= int(input("enter second value"))
        except ValueError:
            print("Please enter a number")
            main()

So if I enter a letter instead of number the exception is caught, but how do I go back to printing the statement in try block to allow to add a number. I added the main() command but it works only for the first variable cause if the exception is in the second variable it goes back to taking input of first value.

Below is the output of the above code:

Enter first value: a
Please enter a number
Enter first value 5
Enter second value a
Please enter a number
Enter first value 5

The last statement should go back to second try instead of first.

1 Answers

I would do it like this:

def getn(s):
    while True:
        try:
            a = int(input(f"Enter {s} value"))
            break
        except ValueError:
            print("Please enter a number")
    return a

def main():

    while True:
        a= getn("first")
        b= getn("second")
    
main()

of course you can put the logic in main as well..

Related