Untitled

mail@pastecode.io avatar
unknown
python
3 years ago
2.2 kB
3
Indexable
Never
# Tuples are immutable. So how can we modify a tuple? Let's find out

class TupleMenu():
    def __init__(self):
        self.user_tuple = tuple(("Chevy", "Ford", "Hyundai", "Mazda",))
        self.menuoptions()
    

    def menuoptions(self):
        options = {
            "1": self.createentry,
            "2": self.readentries,
            "3": self.updateentry,
            "4": self.deleteentry
        }

        choice = input(
            """Which operation would you like to perform?\n
            1. Create Entry\n
            2. Read Entries\n
            3. Update Entry\n
            4. Delete Entry\n\n
            Choice: """)
        if choice not in options: self.menuoptions()
        options[choice]()


    def createentry(self):
        val = input("What would you like to insert?: ")

        print(f"\n{val}: pair has been added\n")
        self.user_tuple += val
        self.menuoptions()


    def updateentry(self):
        upd = input(f"What would you like to update?\n (0-{len(self.user_tuple)-1} OR specify a string): ")
        new_val = input(f"What would you like the new value of {upd} to be?: ")
        mutable = list(self.user_tuple)

        if not upd.isdigit():
            for ind, val in enumerate(mutable):
                if val == upd:
                    mutable[ind] = new_val
                    self.user_tuple = tuple(mutable)
                    return self.menuoptions()
            print("That value doesn't exist!")
        else:
            mutable[int(upd)] = new_val
            self.user_tuple = tuple(mutable)
        return self.menuoptions()


    def readentries(self):
        for val in self.user_tuple:
            print(f"\n{val}\n")
        return self.menuoptions()
    

    def deleteentry(self):
        val = input(f"What value would you like to delete? (0-{len(self.user_tuple)-1} OR specify a string): ")
        mutable = list(self.user_tuple)

        if not val.isdigit():
            mutable.remove(val)
        else:
            mutable.pop(int(val))
        self.user_tuple = tuple(mutable)
        self.menuoptions()


new_tuple = TupleMenu()