Exercise
Building A Stack Using Lists
Objective
Develop a program in Python to implement a stack using a list. The program should support operations to push elements onto the stack, pop elements from the stack, and display the current contents of the stack. Include error handling for attempting to pop from an empty stack.
Example Python Exercise
Show Python Code
class Stack:
"""Class to implement a stack using a list."""
def __init__(self):
"""Initializes the stack as an empty list."""
self.stack = []
def push(self, item):
"""Adds an item to the top of the stack."""
self.stack.append(item)
print(f"Item '{item}' pushed onto the stack.")
def pop(self):
"""Removes and returns the top item from the stack."""
if self.is_empty():
print("Error: The stack is empty. Cannot perform pop.")
else:
item = self.stack.pop()
print(f"Item '{item}' popped from the stack.")
return item
def is_empty(self):
"""Checks if the stack is empty."""
return len(self.stack) == 0
def display(self):
"""Displays the current contents of the stack."""
if self.is_empty():
print("The stack is empty.")
else:
print("Current contents of the stack:", self.stack)
def main():
"""Main function to interact with the stack."""
s = Stack()
while True:
print("\nOptions:")
print("1. Push (Add item to the stack)")
print("2. Pop (Remove item from the stack)")
print("3. Display stack contents")
print("4. Exit")
choice = input("Choose an option (1/2/3/4): ")
if choice == "1":
item = input("Enter the item to push onto the stack: ")
s.push(item)
elif choice == "2":
s.pop()
elif choice == "3":
s.display()
elif choice == "4":
print("Exiting the program.")
break
else:
print("Invalid option. Please choose a valid option.")
# Run the program
if __name__ == "__main__":
main()
Output
Options:
1. Push (Add item to the stack)
2. Pop (Remove item from the stack)
3. Display stack contents
4. Exit
Choose an option (1/2/3/4): 1
Enter the item to push onto the stack: Book
Item 'Book' pushed onto the stack.
Options:
1. Push (Add item to the stack)
2. Pop (Remove item from the stack)
3. Display stack contents
4. Exit
Choose an option (1/2/3/4): 3
Current contents of the stack: ['Book']
Options:
1. Push (Add item to the stack)
2. Pop (Remove item from the stack)
3. Display stack contents
4. Exit
Choose an option (1/2/3/4): 2
Item 'Book' popped from the stack.
Options:
1. Push (Add item to the stack)
2. Pop (Remove item from the stack)
3. Display stack contents
4. Exit
Choose an option (1/2/3/4): 3
The stack is empty.
Options:
1. Push (Add item to the stack)
2. Pop (Remove item from the stack)
3. Display stack contents
4. Exit
Choose an option (1/2/3/4): 4
Exiting the program.
Share this Python Exercise