How to Print a Specific Item in a List if the Input is outside of index

Viewed 41

I'm trying to have this code return a list item if it's within the index, but if it's not in the index to just default to a specific item in the index

Below code is an example:

messages = ["Hello", "Howdy", "Greetings"]
user_num = int(input("Enter a Number Between 1-3: "))
def message_prompt(num):
    num_check = num - 1
    message = messages[num_check]
    if message in messages:
        print(message)
    else:
        print(messages[2])
message_prompt(user_num)

With this code it just errors out at message because the variable is outside of the scope of the index. What can I do to fix this?

3 Answers

Python does not support indexing a list with an invalid index. One idiomatic solution is to use try / except:

messages = ["Hello", "Howdy", "Greetings"]
user_num = int(input("Enter a Number Between 1-3: "))

def message_prompt(num):
    try:
        print(messages[num - 1])
    except IndexError:
        print(messages[2])

message_prompt(user_num)

Do note that negative indices are permitted. So the above solution won't error if -2 is input; in this case, the penultimate list item will be printed.

If you rather use ask permission you can test first:

messages = ["Hello", "Howdy", "Greetings"]
user_num = int(input(f"Enter a Number Between 1-{len(messages)}: ")) - 1 # make it zero based

def message_prompt(num):
    print(messages[num if num < len(messages) else -1]) # default to the last one

message_prompt(user_num)

although python propagates "Ask forgiveness not permission" (i.e. try: ... except: ...)

This num if num < len(messages) else -1 is a ternary expression that uses num if small enough else defaults to -1 (the last element).

See: Does Python have a ternary conditional operator?

you can use try except, or validate the value in a while loop until a legal input is specified:

messages = ["Hello", "Howdy", "Greetings"]
user_num = int(input("Enter a Number Between 1-3: "))
def message_prompt(num):
num_check = num - 1
    try:
        message = messages[num_check]
        print(message)

    except IndexError:
        print(messages[2])

message_prompt(user_num)

i recommend on reading on try except block to protect from user input.

Related