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?
-
2your 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– Paritosh Singh2019年01月14日 16:47:10 +00:00Commented Jan 14, 2019 at 16:47
3 Answers 3
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).
Comments
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.
Comments
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.