[英]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.
如果这不是有效整数,则int函数将引发异常。
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.
列表的第一个元素位于索引#0,最后一个元素是# list-length - 1。例如,3 项列表的元素位于 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.