简体   繁体   English

您如何让用户输入一个数字并让该数字从列表中提取该数据单元格值?

[英]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.

相关问题 在 Python 中,如果您有两个共享多个元素的列表,您如何创建具有匹配项的新列表? - In Python, if you have two lists that share a number of elements, how do you create a new list with the matches? 我如何让用户输入列表? - How do I have a user input a list? 如何将列表和用户号码传递给函数并让它显示列表中大于用户号码的所有数字? - How do I pass both the list and the user's number to a function and have it display all numbers in the list that are greater than the user's number? 我如何让 Python 程序用户选择要从中提取的列表? - How do I have the Python program user choose the list to pull from? 如何将用户输入中的数字附加到列表中? - How to append a number from user input to list? 我该如何接受用户输入的等边多边形的边数,并用乌龟绘制它 - how do i take a user input for the number of sides in an equilateral polygon and have turtle draw it Python 如果值是一个列表并且我有列表中的第一个数字,我如何搜索字典? - Python How do I search through a dictionary if the the value is a list and I have the first number in the list? 如何让用户从列表中提取数据并将其清晰地显示在 output 中? - How to have a user pull data from lists and display it cleanly in output? 如何使用Beautiful Soup提取具有某些类属性的列表项? - How do you use Beautiful Soup to pull out list items that have certain class attributes? 我想从另一个列表中的列表中提取一个数字,我该怎么做? - I want to pull a number from a list inside another list, how do I do it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM