0

I have this function where the user is supposed to give a number. I am having a little issue with my try function. If I enter a string like "abc", it will first tell me to give an integer. So when I write "123" next time, it won't work. This is what I receive then:

UnboundLocalError: local variable 'limit' referenced before assignment

My code:

def limitchooser()
     try:
          limit = int(input("Enter your limit: "))
     except ValueError:
          print("Please enter an integer!")
          limitchooser()
     return limit
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Performing input validation using recursion is dangerous, because the program will crash with `maximum recursion depth exceeded` if the user enters invalid data too many times in a row. [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) might be useful to you. – Kevin Dec 15 '14 at 17:27

1 Answers1

1

You are ignoring the return value of a recursive call, so in the function where there was a ValueError exception, limit is never set.

You want to assign the returned value from recursive calls:

def limitchooser()
     try:
          limit = int(input("Enter your limit: "))
     except ValueError:
          print("Please enter an integer!")
          limit = limitchooser()
     return limit

Better still, don't use recursion. Any sufficiently determined user will break your recursion limit instead. Use a loop here:

def limitchooser()
     while True:
         try:
              return int(input("Enter your limit: "))
         except ValueError:
              print("Please enter an integer!")

The while True: creates an infinite loop, but the return will exit the function breaking the loop (provided an integer was entered).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343