在Python中由用户输入给定的索引处打印值 [英] Print value at index given by user input in Python

查看:46
本文介绍了在Python中由用户输入给定的索引处打印值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用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.

我有一个值列表.
我想提示用户输入.
然后打印出列表中相应索引号处的值.

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 (......)

如果用户输入2,我想打印索引2(20)上的值.我不确定打印后要放什么.

If the user inputs 2, I want to print the the value that is at the index 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.

我假设用户提供的输入将是一个字符串,因此我们需要使用 int()将其更改为整数.

The input given by the user I assume would be a String, so we need to use int() to change it to an integer.

print myList[int(choice)]

此外,您可能需要首先检查提供的输入的有效性;它不能小于0或大于列表的长度-1;

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;

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

这篇关于在Python中由用户输入给定的索引处打印值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆