我正在尝试制作一个遍历列表中所有项目的代码:
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:字符串索引超出范围“
print("Do you want %s, %s, or %s?" % (lunch[a],lunch[a+1],lunch[a+2]))
我知道这意味着索引大于或小于它可以索引的索引(大于或小于列表长度减去1),但它不应该这样做,因为它从零开始并结束列表结束前的四个。
答案 0 :(得分:2)
问题在于我覆盖了变量public void draw(Graphics2d g2)
,就像Aiven所说的那样。感谢
答案 1 :(得分:-2)
您的问题是lunch[a+n]
中对索引的引用超出范围。您可以代表您的选择。
lunch = ['pasta', 'pudding', 'cereal', 'steak']
print('Would you like {0} or {1} or {2} or {3}'.format(*lunch))