How to solve i++ loop error in Python? -
my code giving following error: indexerror: list index out of range know if there way use similar i++ loop java in python code print "name" + iten list every iten of list positioning.
sorry if seems bit confusing beginner hard explain somethings :p
ex:
i = 0 "name" + list[0] = 1 "price" + list[1] = 2 "name" + list[2]
code:
import pickle list1 = [] ans = " " class product: def __init__(self, name, price): self.name = name self.price = price while ans != 'no': ans = input("would add new product, 'yes' or 'no': ") if ans == 'no': break if ans == 'yes': name = input("what product name?") price = input("what product price?") list1.append(name) list1.append(price) output = open("save1.pkl", 'wb') pickle.dump(list1, output,pickle.highest_protocol) output.close() print(" ") inputfile = open("save1.pkl", 'rb') list2 = pickle.load(inputfile) inputfile.close() in range(0,10): print("name:" + list2[i] + " " + "price:" + list2[i + 1])
so looks you've got list
indices name
s, , odd indices price
s. don't want or need indexing here, because python has better solutions problem c. combine extended slicing zip
iterate them natively in pairs:
for name, price in zip(list2[::2], list2[1::2]): print("name:" + name + " " + "price:" + price)
the list2[::2]
getting every other element beginning end, while list2[1::2]
gets every other element index 1 end. zip
returns tuple
s of paired values each slice, value @ index 0 , 1 first name
, price
, 2 , 3 give second name
, price
, etc. unpack them meaningful names in loop itself, instead of working indices of list2
cryptic meanings, it's clear we've got name , price.
Comments
Post a Comment