user152573
user152573

Reputation: 103

How do I deal with exceptions in a for loop?

Here is an example of a random piece of python loop code:

for j in range(5):
    try:
        cats = raw_input("Enter age of your five cats")

    except ValueError:
        print ("Try again")

The problem I have with this code is that when ever the except line is triggered, my loop does not completely reset itself. What happens is that when I get an exception, the exception itself counts as 1 for the range..

More specific:

Lets say the user does not trigger exception and we get these 5 age inputs 5 4 5 3 2 (range 5), however if we do trigger an exception then the user is only allowed to enter 4 ages 5 4 5 3 because for some reason the exception counts towards the range count..Does anyone know how to fix this issue?

Upvotes: 0

Views: 161

Answers (3)

paxdiablo
paxdiablo

Reputation: 882776

You could do something like:

for j in range (5):
    badCat = True
    while badCat:
        try:
            cats[j] = int (raw_input ("Enter age of cat # %d: " % (j + 1)))
            badCat = False
        except ValueError:
            print ("Try again")

This will stay on a single cat until you enter a "proper" age.

You'll notice I've wrapped an int() around your input function call. I assume that's what you were going to do eventually since I'm pretty certain raw_input() doesn't throw ValueError on its own.

I've also stored the age of the cat in an array since your code will only ever remember the last age entered.

You can remove the need for a separate variable (if you're worried about that sort of thing (which I tend not to be)) by making a slight modification:

for j in range (5):
    while True:
        try:
            cats[j] = int (raw_input ("Enter age of cat # %d: " % (j + 1)))
            break;
        except ValueError:
            print ("Try again")

Upvotes: 3

Martin Konecny
Martin Konecny

Reputation: 59701

Stay in a while loop inside of your for loop until you get the input you want.

for j in range(5):
    input_ok = False
    while not input_ok:
        try:
            cats = raw_input("Enter age of your five cats")
            input_ok = True
        except ValueError:
            print ("Try again")

This way you will only enter the next iteration of your outer for loop when you get a valid cat age value.

Upvotes: 1

franzwr
franzwr

Reputation: 106

Maybe...

for j in range(5):
    while True:
        try:
            cats = raw_input("Enter age of your five cats")
            break

        except ValueError:
            print ("Try again")

Upvotes: 0

Related Questions