使用输入法从列表中选择一个项目[重复]

问题描述 投票:0回答:1

我想使用输入法从列表中选择一个项目。我是初学者,我只是想使用我的逻辑。

name_list = ["apple", "banana", "orange"]
choice = input("Enter your name here: ")
print(name_list[choice] -1)

它给我一个错误:“列表索引必须是整数或切片,而不是 str”

我的代码有什么问题?

我希望控制台打印出一个项目。例如,如果用户输入 1,控制台应打印出:“apple”

python list input
1个回答
0
投票

正如之前的评论所指出的错误,这里有一些详细说明,以防您不明白。

你的代码的问题是 input() 函数返回一个字符串,但你正试图将它用作索引来访问列表中的元素。列表索引必须是整数,而不是字符串。

请注意,我们从选择中减去 1,因为列表索引从 0 开始,而不是 1,您已经知道了。

所以简单的解决方法就是改变这个:

choice = int(input("Enter your number here: "))  # an integer number expected

# and fix this line too:
print(name_list[choice -1])
© www.soinside.com 2019 - 2024. All rights reserved.