调试Python中嵌套的for循环

2024-10-01 00:25:09 发布

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

这是一个Python项目。一旦满足条件,while循环似乎不会停止,并且我的程序返回一个错误,它声称“列表索引超出范围”,有没有发现我的错误?它似乎位于变量“v”中,没有按需要递增。在

代码:

import csv
file = open("stocklist.csv","r")

stocklist = csv.reader(file)

slist = []
quant = []
x = "yes"
amofitems = 0

while x != 'no':
    GTIN = input("What is the GTIN-8 number of your desired item? ")
    slist.append(GTIN)
    #quan = input("How many of this item do you require? ")
    #quant.append(quan)
    amofitems = amofitems + 1
    x = input("Do you wish to purchase another item? Yes/No ").lower()

product = []
v = 0

while v < amofitems:
    for row in stocklist:
        print(row)
        for item in row:
            print(item)
            if item == slist[v]:
                print("Object found")
                product.append(row[1])
                quant.append(row[2])
            print("row:",v)

        v = v + 1
        print("V:",v)

print ("Your selected item is", product, "with a price of")   
file.close()

Tags: ofcsvinputproductitemfilerowprint
1条回答
网友
1楼 · 发布于 2024-10-01 00:25:09

看起来v不应在for循环中递增,而该代码部分应该是:

while v < amofitems:
    for row in stocklist:
        print(row)
        for item in row:
            print(item)
            if item == slist[v]:
                print("Object found")
                product.append(row[1])
                quant.append(row[2])
            print("row:",v)

    v = v + 1        # different indentation here
    print("V:",v)

请注意,通常有几种方法可以整理代码。例如,可以通过使用enumerate来避免完全维护索引:

^{pr2}$

相关问题 更多 >