4

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?

TheStrangeQuark
  • 1,704
  • 2
  • 18
  • 46
  • 2
    your own sentence has the hint."return a list item **if** it's within the index, **but**... " Why dont you do an if check to see if the input number would be within the index range for the list? – Paritosh Singh Jan 14 '19 at 16:47

3 Answers3

2

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.

jpp
  • 134,728
  • 29
  • 196
  • 240
2

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?

Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
0

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.

masasa
  • 202
  • 1
  • 7