Jay Gattuso
Jay Gattuso

Reputation: 4130

Python - return to the start of a function if an invalid input is made?

I'm trying to catch an input error - where the only valid input is an integer.

If a non integer is input, I want it to return to the start of func and try again:

def setItorator():
 try:
  iterationCap = int(raw_input("Please enter the number of nibbles you want to make: "))
  print "You will make", iterationCap, "nibbles per file"
 except ValueError:
  print "You did not enter a valid integer, please try again"
  setItorator()
 return iterationCap 

if __name__ == "__main__":
 iterationCap = setItorator()

This method works if the first input is valid, and returns to the start of the func if a non valid input is made, but it does not seem to pass the correct valid back to the main func. I checked in the sub func that it sees the correct variable, and of the correct type (int) and it does appear to, but I get an error:

UnboundLocalError: local variable 'iterationCap' referenced before assignment  

I do not see this error if the first input is valid (e.g. "10") only if the first input is not valid (e.g. "a" followed by "10")

Upvotes: 3

Views: 5058

Answers (2)

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72815

Try something like this.

while True:
   try:
    i = int(raw_input("Enter value "))
    break
   except ValueError:
    print "Bad input"

print "Value is ",i

Your current approach will recursively call your function for every error which is not a good practice. The error is because inside your exception handler block, you're not defining iterationCap.

Upvotes: 3

jadkik94
jadkik94

Reputation: 7078

You need to return setItorator() in the except statement. Right now, you're just calling the function and ignoring the output.

Upvotes: 2

Related Questions