Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python try/exception help

I'm trying to support repetition where the user inputs a filename, then inputs two integers. So if an exception is thrown, I want the user to be prompted with input again.

My problem is if a valid file is entered but an invalid integer is entered it will ask for the file again instead of just the integer. How can I fix the code so it will ask for the integer again.

Here is what I have:

while True:
    try:
        f = raw_input("Enter name of file: ")
        inFile = open(f)
        # more code
    except IOError:
        print ("The file does not exist. Try Again.")        
    else:    
        try:
            integer = int(raw_input("Enter an integer: "))
            integer2 = int(raw_input("Enter an integer: "))
            # more code
        except (TypeError, ValueError):
            print ("Not an integer. Try Again.")
like image 320
michael Avatar asked Jan 30 '26 23:01

michael


1 Answers

Try use multiple while loops:

while True:
    fileName = raw_input("Enter name of file: ")
    try:
        # more code here to detect or open the file
        break
    except Exception:  # can be IOError or something else
        print ("error msg")

while True:
    try:
        integer = int(raw_input("Enter an integer: "))
        integer2 = int(raw_input("Enter an integer: "))
        break
    except (TypeError, ValueError):
        print ("error msg")

# more code
like image 69
Wang Dingwei Avatar answered Feb 01 '26 12:02

Wang Dingwei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!