简体   繁体   中英

How do you have a user input a number and have that number pull that data cell value from a list?

For the task that I have been assigned, you are told that when a person enters a number, that data cell value should be pulled from the list. How do I achieve this?

I assume you mean "data cell value" as "list item" at an index.

First there is input from the user, using the input function. If this is not a valid integer, the int function will raise an exception.

Then we must also check that the index given by the user is within the list size. The first element of a list is at index #0, and the last is # list-length - 1. For example, a 3-item list has elements at 0, 1, 2.

fruit = [ "Apples", "Oranges", "Rambutan", "Mango" ]

try:
    user_text = input("Enter fruit index: ")
    user_choice = int(user_text)
except:
    print("Bad Choice");
    user_choice = -1

if (user_choice >= 0 and user_choice < len(fruit)):
    print("Your Fruit is: " + fruit[user_choice])
else:
    print("Index out of range")

Eg:

# python3 ./fruit.py 
Enter fruit index: 2
Your Fruit is: Rambutan

# python3 ./fruit.py 
Enter fruit index: None of your business
Bad Choice
Choice out of range

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM