Davy Karlsson
Davy Karlsson

Reputation: 887

Stopping a loop and returning the value if it doesn't give an error

I have this function:

def int_input(promt):
    while True:
            try:
                    int(promt)
            except ValueError:
                    print "Not a number, try again."
                    promt = raw_input("Enter your choice:")

I want it to break at some point to return promt if it is a number, and I can't seem to find a reasonable way.

Upvotes: 0

Views: 51

Answers (4)

petebachant
petebachant

Reputation: 87

Ngenator's answer is a bit cleaner, but you could set a variable as a switch to indicate you got a correct value:

def int_input(promt):
    got_int = False
    while not got_int:
            try:
                    int(promt)
                    got_int = True
            except ValueError:
                    print "Not a number, try again."
                    promt = raw_input("Enter your choice:")

Upvotes: 0

Ngenator
Ngenator

Reputation: 11259

Not 100% sure what else you're doing, but if you call this, it will not return until you input a valid int.

def int_input():
    while True:
        try:
            return int(raw_input("Enter your choice:"))
        except ValueError:
            print "Not a number, try again."

print int_input()

output

Enter your choice: asdf
Not a number, try again.
Enter your choice: 2df
Not a number, try again.
Enter your choice: 3
3

Upvotes: 4

ch3ka
ch3ka

Reputation: 12158

try..except has an optional else clause:

def int_input(promt):
    while True:
            try:
                    int(promt)
            except ValueError:
                    print "Not a number, try again."
                    promt = raw_input("Enter your choice:")
            else: # no exception occured, we are safe to leave this loop
               break # or return, or whatever you want to do...

but this is not neccessary here, you can simply return or break inside the try (after the int() cast. will only get reached when there wasn't an exception during int()).

Upvotes: 0

Ayb4btu
Ayb4btu

Reputation: 3388

Does this do what you want:

def int_input(promt):
    while True:
        try:
            int(promt)
        except ValueError:
            print "Not a number, try again."
            promt = raw_input("Enter your choice:")
            continue

        return int(promt)

Upvotes: 0

Related Questions