繁体   English   中英

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

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

对于分配给我的任务,您被告知当一个人输入一个数字时,应从列表中提取该数据单元格值。 我如何实现这一目标?

我假设您的意思是“数据单元格值”作为索引处的“列表项”。

首先是来自用户的输入,使用输入函数。 如果这不是有效整数,则int函数将引发异常。

然后我们还必须检查用户给出的索引是否在列表大小之内。 列表的第一个元素位于索引#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")

例如:

# 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.

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