Search code examples
pythonvalidationinteger

Python: Validation problem for specific ints


I have a list, list = ["Dog", "Cat"] and printed out an enumerated list, e.g. 0 Dog 1 Cat

I want the get the user to choose one (using an input command) Then I want to validate the input to make sure it's 0,1 (with future versions going from 0 to 20 for other animals too). My attempt at validation uses some help I recently received (tq) to make sure the input was an int. I've added a further check, to make sure that the int was one of the acceptable numbers, by previously dumping the animal lists index (when printing the enumerated animal list), into a new list [0,1] called "list_with_valid_numbers_to_choose_from". I want to print out the users number input at the end. It all works perfectly, EXCEPT when I input a zero, then I get "True" as the result and not what I want, which is 0. I've tried a few ways to force an actual 0 number to be returned but have run out of ideas.

def get_number(no_elements, list_with_valid_numbers_to_choose_from):
        while True:
            print(f"no_elements= {no_elements}") # I don't actually use no_elements in this function.
            value = input("Enter the number of the animal you want to choose: ")
            try:
                if value := int(value) or value == "0":   # Conversion to an int was fine
                    # now check to see if the int is a valid option
                    for element in list_with_valid_numbers_to_choose_from:      # e.g. [0,1] from ["Dog", "Cat"]
                        if element == value:
                            print(f"value= {value}")
                            if value == 0:
                                del(value)
                                value=0
                                return 0
                            return value
                raise ValueError("There are no animals (check to see if you created one earlier), OR, you didn't enter a valid number according to the choices given")
            except ValueError as e:
                print(e)

If say the returned 'True', is because the condition of the while True statement was met, then how on earth to escape this and actually return a variables value?


Solution

  • This is a briefer way to do this, using builtin methods.

    def get_number(valid_numbers):
        while True:
            input_value = input("Enter the number of the animal you want to choose")
            if not input_value.isnumeric():
                print('Non-integer value entered')
            else:
                number = int(input_value)
                if number in valid_numbers:
                    return number
                print('Animal not found')