#๐Ÿ”’ Input Validation List index Out of Range

40 messages ยท Page 1 of 1 (latest)

earnest wolf
#

I have a data validation function:

# Function to validate user input
def get_valid_choice(i):
    while True:
        try:
            user_input = int(input("Enter the number of your choice: "))
            if 1 <= user_input <= len(i):
                return user_input
            else:
                print(f"Please enter a number between 1 and {len(i) - 1}.")
        except ValueError:
            print("Invalid input. Please enter a number.")

which is working fine when im sending it the length of a list in one function (choose_race) but not in the other similar function (choose_gender), and im not sure why. It's saying choose between 1 and 3, but the list only has 2 items in it.

def choose_race():
    #TODO from races.py list races dict and make a choice
    print("What Race are you?")
    # Display numbered choices
    for index, i in enumerate(race_list, start=1):
        print(f"{index}. {i['race_name']}")
    
    # Get and validate user choice
    selected_index = get_valid_choice()
    selected_choice = race_list[selected_index - 1]
    return selected_choice

def choose_gender():
    gender_choices = ['Male', "Female"]
    print(f"length of gender_choices is: {len(gender_choices)}")
    print("Which gender are you?")
    print(gender_choices) # shows 2 entries in list at index positions 0 and 1

    # Display numbered choices
    for index, i in enumerate(gender_choices, start=1): # start at 1 instead of index 0, real start
        print(f"{index}. {i}")
    # Get and validate user choice
    selected_index = get_valid_choice()
    selected_choice = gender_choices[selected_index - 1] # minus 1 to get actual index position
    return selected_choice
stray muralBOT
#

@earnest wolf

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

sour dawn
#

your function get_valid_choice expects an input
but you didnt give an input selected_index = get_valid_choice()

#

selected_index is probably empty

#

try to print(selected_index)

earnest wolf
#

think i pasted in the old thing, still had my vaildate function in same file before refactoring out, 2 secs

#
def choose_race():
    #TODO from races.py list races dict and make a choice
    print("What Race are you?")
    # Display numbered choices
    for index, i in enumerate(race_list, start=1):
        print(f"{index}. {i['race_name']}")
    
    # Get and validate user choice
    selected_index = get_valid_choice(i)
    selected_choice = race_list[selected_index - 1]
    return selected_choice

def choose_gender():
    gender_choices = ['Male', "Female"]
    print(f"length of gender_choices is: {len(gender_choices)}")
    print("Which gender are you?")
    print(gender_choices) # shows 2 entries in list at index positions 0 and 1

    # Display numbered choices
    for index, i in enumerate(gender_choices, start=1): # start at 1 instead of index 0, real start
        print(f"{index}. {i}")
    # Get and validate user choice
    selected_index = get_valid_choice(i)
    selected_choice = gender_choices[selected_index - 1] # minus 1 to get actual index position
    return selected_choice

# Function to validate user input
def get_valid_choice(i):
    while True:
        try:
            user_input = int(input("Enter the number of your choice: "))
            if 1 <= user_input <= len(i):
                return user_input
            else:
                print(f"Please enter a number between 1 and {len(i)}.")
        except ValueError:
            print("Invalid input. Please enter a number.")
#

so it works with choose_race but same thing doesnt with choose_gender

#

as usual gonna be something stupid im just not seeing

sour dawn
#

can you do print(selected_index)
maybe that variable is different to what you expect

earnest wolf
sour dawn
#

4 is way out of range

earnest wolf
#

so it should see that and go nope and ask again

#
# Function to validate user input
def get_valid_choice(i):
    while True:
        try:
            user_input = int(input("Enter the number of your choice: "))
            if 1 <= user_input <= len(i):
                return user_input
            else:
                print(f"Please enter a number between 1 and {len(i)}.")
        except ValueError:
            print("Invalid input. Please enter a number.")```
sour dawn
#

i see the problem

earnest wolf
#

in the else statement

sour dawn
#

selected_index = get_valid_choice(i)

#

i is a word in this case

#

selected_index = get_valid_choice(gender_choices) should work

earnest wolf
#

success

#

let me try wrap my head round it

#

i though i, was the index position

#

so 0 and 1 for this 2 index list

sour dawn
#

yeah, index 4 in 'woman' works
you called the function with i which was 'woman'

#

you need to call the function with the list

earnest wolf
#

knew it'd be something stupid

#

always is

sour dawn
#

happens

#

i would recommend better variable names

earnest wolf
#

thanks you!

sour dawn
#

instead of i use something more descriptive

earnest wolf
#

yeah, i will try to

#

save me grief

#

again, truly appreciated

sour dawn
#

no problem

earnest wolf
#

!close

stray muralBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.