Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to print out something instead of geting an error when list.pop function is out of range?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading