user input that references to values of a list in python

To reference values of a list in Python using user input, we can follow these steps:

  1. Create a list with some values.
  2. Take user input as an index value.
  3. Use input validation to make sure the user input is within the range of the list indices.
  4. Use the index value to access the corresponding value in the list.
  5. Print the value.

Here is an example code snippet to demonstrate this:

main.py
# create a list
my_list = [10, 20, 30, 40, 50]

# take user input for index value
index = input("Enter an index value: ")

# validate user input
if not index.isdigit():
    print("Invalid input: Enter a positive integer.")
elif int(index) >= len(my_list):
    print(f"Invalid input: Index should be less than {len(my_list)}.")
else:
    # access the value using index value
    value = my_list[int(index)]
    # print the value
    print(f"The value at index {index} is {value}.")
481 chars
17 lines

In this code snippet, we first create a list my_list with some values. Then, we take user input for the index value using the input() function. We then use input validation to make sure that the user input is a positive integer and within the range of the list indices. If the input is valid, we use the index value to access the corresponding value in the list. Finally, we print the value.

gistlibby LogSnag