Python错误“索引器错误:字符串索引超出范围”

2024-04-26 22:00:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试生成一个代码,可以遍历列表中的所有项目,这里:

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。在


Tags: or项目代码youtrue列表inputif
2条回答

问题是我过度编写了变量lunch,正如Aiven所说。谢谢

您的问题是对lunch[a+n]中索引的引用超出了范围。你可以这样代表你的选择。在

lunch = ['pasta', 'pudding', 'cereal', 'steak']

print('Would you like {0} or {1} or {2} or {3}'.format(*lunch))

相关问题 更多 >