My training course task is to make a shoppingcart, everything works as intented but I can’t figure out the function pop out of range problem.
My code:
# -*- coding: cp1252 -*-
class Cart:
shoppingcart = []
def addstuff(self):
esine = input("What will be added?: ")
self.shoppingcart.append(esine)
def remove(self):
esine2 = input("Which item is deleted?: ")
self.shoppingcart.pop(int(esine2))
def main():
customer = Cart()
while True:
selection = input("Would you like to \n"
"(1)Add or \n"
"(2)Remove items or \n"
"(3)Quit: ")
if selection == "1":
customer.addstuff()
if selection == "2":
print("There are", len(customer.shoppingcart), "items in the list.")
customer.remove()
if selection == "3":
print("The following items remain in the list:")
for i in \
customer.shoppingcart:
print(i)
break
if selection > "3":
print("Incorrect selection.")
if __name__ == "__main__":
main()
Problem is while deleting(poping) an item that is out of range it gives an error but instead should print out "incorrect selection."
I tried adding if True and else argument into def remove part but that doesn’t help.
>Solution :
Use try except blocks.
emptylist = []
try:
emptylist.pop()
except IndexError:
print('pop failed')
In your code:
def remove(self):
esine2 = input("Which item is deleted?: ")
try:
self.shoppingcart.pop(int(esine2))
except IndexError:
print('no item at index {}'.format(int(esine2))
Do note that pop(i) removes the item in the list at place i, not the item with value i.