Python Forum

Full Version: while with try and except gets stuck in an endless loop?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am working on input validation to validate integer input and index range. My def inputNumber(message) function works as I use it in other areas of my program and it functions as expected. However, my def withinRange(myList, choice) function throws an error appropriately but I get stuck in an endless loop. My code is provided below any help or suggestions are appreciated in advance.

def inputNumber(message):
    #input validation to ensure user enters a number
    while True:
        try:
            userInput = int(input(message))
        except ValueError:
            print('That is not a number! Try Again!')
            continue
        else:
            return userInput
            break
def withinRange(myList, choice):
    while True:
        try:
            result = myList[choice-1]
        except IndexError:
            print('That number is not a valid choice! Try Again!')
            continue
        else:
            return result
            break
choice = withinRange(resultsList,inputNumber('Select your new username by entering the number above:\n'))
The first, inputNumber has a way of changing userInput
The second withinRange takes in a value that is not altered within the loop.
Ask for a number within the while loop, not outside of it.

Like this:
def withinRange(myList, choice_getter, message):
    while True:
        choice = choice_getter(message)
        try:
            result = myList[choice-1]
        except IndexError:
            print('That number is not a valid choice! Try Again!')
            continue
        else:
            return result

choice = withinRange(resultsList, inputNumber, 'Select your new username by entering the number above:\n')
Or, if you're comfortable with partial functions, this is a cleaner looking way:
import functools

def withinRange(myList, choice_getter):
    while True:
        choice = choice_getter()
        try:
            result = myList[choice-1]
        except IndexError:
            print('That number is not a valid choice! Try Again!')
            continue
        else:
            return result

getter = functools.partial(inputNumber, 'Select your new username by entering the number above:\n')
choice = withinRange(resultsList, getter)
That's the same as this:
getter = lambda: inputNumber('Select your new username by entering the number above:\n')
Nilamo the second option you provided worked like a charm. Thank you!