Search code examples
pythonrecursiontry-except

Python: try/except call returning wrong value, calling except clause unneeded


In the attached code snippet the goal is to receive a user input and, depending if it is an integer or not, return the integer or call the function recursively until a valid integer is given.

def verify_input(msg, str_exp=True, req_str=None):
    user_input = input(msg)
    if str_exp:
        pass # TODO: implement later
    else:
        try:
            return int(user_input)
        except ValueError:
            verify_input("Enter a whole number please. ", str_exp=False)

If user responds correctly (i.e. an integer) on the first function call the integer is indeed returned from the function.

Problem is, if user misbehaves and firstly doesn't respond with an integer, only giving integer on subsequent tries, I can see, working with a debugger, that the try clause always goes to the except clause... even though the second call is with an integer.

To sum up:
verify_input(12) # => returns 12
verify_input("Hello") # => return a call to verify_input ---> user gives answer "12" => returns None.

Thanks in advance.


Solution

  • You're missing a return when you call verify_input in the except ValueError block:

    try:
        return int(user_input)
    except ValueError:
        return verify_input("Enter a whole number please. ", str_exp=False)