Python报错IndexError: list out of range 访问ItemNumber数组非首元素出错
错误原因
- 逻辑混淆导致
ItemNumber数组长度不足:你将卖家ID错误存进了本应存储商品编号的ItemNumber数组,且整个流程仅向该数组插入了1个元素,后续遍历要访问索引0~9共10个位置,访问索引≥1时就会触发越界错误。 choice1 == "yes"分支逻辑完全失效:初始化阶段ItemNumber是空数组,for i in ItemNumber的循环永远不会执行,该分支下不会往ItemNumber插入任何数据,也不会执行添加商品的逻辑,后续访问任意索引都会报错。- 存在语法错误:最后遍历商品的循环关键字
for被误写为or,运行时会直接触发语法错误。
修复方案
首先理清核心逻辑:ItemNumber/ItemDescription/ItemReserveprice/ItemBids四个数组的每个下标对应同一个商品的四类信息,10个商品需要每个数组都有10个元素,卖家ID单独存储不要和商品编号混淆。
修复后的可运行代码如下:
ItemNumber = [] ItemDescription = [] ItemReserveprice = [] ItemBids = [] Item = 0 Buyerno = 1 BuyerNumber = [] sellercount = 0 seller_id = "" # 单独存储卖家ID whoareyou = input("Are you a seller or a buyer? enter s/b ") if whoareyou == "s": choice1 = input("Do you want to enter your seller ID?: ") if choice1 == "yes": seller_id = input("Please enter your seller id in the form 00N: ") elif choice1 == "no": seller_id = '00' + str(sellercount+1) print (seller_id,"is your seller ID") # 统一处理10个商品录入,两个分支都要走 while Item < 10: print ("Now enter Item number",Item+1) # 给每个商品生成编号存入ItemNumber ItemNumber.insert(Item, f'ITEM{Item+1:03d}') ItemDescription.insert(Item,input("Enter your item description: ")) ItemReserveprice.insert(Item,int(input("Enter your reserve price: "))) ItemBids.insert(Item,0) Item = Item + 1 print ("Auction Starts!") print ("You are now in the buyer screen") BuyerNumber.insert(Buyerno,('aa' + str(Buyerno))) print ("Your buyer number is",BuyerNumber) # 修正for关键字错误 for i in range (0,10): print ("The Item number of item number ",i+1,"is",ItemNumber[i],"The Description is",ItemDescription[i],"The reserve price is",ItemReserveprice[i]) choice2 = input("What item do you want to bid for?, enter the item number")
内容的提问来源于stack exchange,提问作者user17493633
相关产品推荐
相关产品推荐

