userValue = 5
selection = []
if userValue == 1:
selection.append("box")
if userValue == 2:
selection.append("ball")
if userValue == 3:
selection.append("pen")
if userValue == 4:
selection.append("pencil")
elif():
print ("please enter a correct value")
print (selection[0])
我正在尝试将值存储在列表中并且它一直给我错误,我不知道该怎么做,任何帮助都将受到高度赞赏。非常感谢提前。 :)
答案 0 :(得分:0)
userValue
在开头设置为5,列表为空。所以,你不会传递任何selection.append()
,因为5不等于1,2,3或4。
您拥有print
条件的elif
语句,然后您尝试访问空列表的第一个元素...这是不可能的,因此会引发异常。<登记/>
顺便说一下,您应该使用else
关键字而不是elif
来使用奇怪的条件。
针对您的问题的更多Pythonic(和工作)解决方案是:
userValue = 5
selection = []
# Create a tuple of string, in the same order as your if before
values = ("", "box", "ball", "pen", "pencil")
if userValue < len(values):
selection.append(values[userValue])
print (selection[0])
else:
print ("please enter a correct value")
答案 1 :(得分:0)
您收到错误,因为列表中没有任何内容。您的每个if
测试均为false,因此不会添加任何内容。您的elif
块也未执行,因为您的测试(空元组)的计算结果为false
。如果你想要一个块,如果前面的块是假的,那么else
将是一个更好的选择。
如果你想在将来防止这样的错误,请确保你有一个else
块,它会在每个if
系列的{{1}}之后添加一些东西到一个空列表中用户输入。
答案 2 :(得分:-1)
sectionvalue [0]错误,因为列表中没有任何内容。 你必须添加任何列表
为什么会有错误 uservalue是5 如果阻止你没有添加条件来检查值5 你使用elif但它永远不会工作它的空元组被评估为false
现在selectionvalue是空的。但是你试图让它的0索引为空 如果你试图在python中访问一个空列表索引,那就会出现错误。你有