简体   繁体   English

在 Python 中用户输入给定的索引处打印值

[英]Print value at index given by user input in Python

I am very new to programming in Python, this is something that seems so simple, but I just don't seem to be able to get it right.我是 Python 编程的新手,这看起来很简单,但我似乎无法做到正确。

I have a list of values.我有一个值列表。
I want to prompt the user for input.我想提示用户输入。
Then print out the value that's at the corresponding index number in the list.然后打印出列表中相应索引号处的值。

myList [0, 1, 20, 30, 40]    
choice = input()    
print (......)

If the user inputs 2, I want to print the the value that is at the index 2 (20).如果用户输入 2,我想打印索引 2 (20) 处的值。 I am unsure of what to put after print.我不确定打印后要放什么。

You can do this by accessing the list using the given input by the user.您可以通过使用用户给定的输入访问列表来执行此操作。

The input given by the user I assume would be a String, so we need to use int() to change it to an integer.我假设用户给出的输入将是一个字符串,因此我们需要使用int()将其更改为整数。

print myList[int(choice)]

Additionally, you may want to first check the validity of the input supplied;此外,您可能需要先检查所提供输入的有效性; it cannot be less than 0, or more than the length of the list - 1;它不能小于 0,也不能大于列表的长度 - 1;

choice = int(choice)
if (choice < 0 || choice >= len(myList))
   print('Not Valid')
else
   print myList[int(choice)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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