我正在尝试生成一个代码,可以遍历列表中的所有项目,这里:
def lunch():
global tl
print("You have %s minutes until school starts." % (tl))
go=True
lunch=["pasta","pb+j","chicken","cheez its","goldfish","pirate's booty","cookie","cupcake","gogurt","strawberries","apple","grapes","carrots","bell peppers","pea pods"]
a=0
while a<len(lunch)-4:
print("Do you pack or buy your lunch? (p,b)")
lunch=input()
if lunch=="pack" or lunch=="p":
go2=True
while go2:
print("Do you want %s, %s, or %s?" % (lunch[a],lunch[a+1],lunch[a+2]))
l=input()
if not(l==lunch[a] or l==lunch[a+1] or l==lunch[a+2]):
print("What?")
else:
print("Yay!")
go2=False
a+=3
但我一直得到错误“IndexError:string index out of range”的行
^{pr2}$我知道这意味着索引大于或小于它可以索引的值(大于或小于列表的长度减去1),但它不应该这样做,因为它从0开始,在列表结束之前结束于4。在
问题是我过度编写了变量
lunch
,正如Aiven所说。谢谢您的问题是对
lunch[a+n]
中索引的引用超出了范围。你可以这样代表你的选择。在相关问题 更多 >
编程相关推荐