← Back to Python List

Question 2: Menu-driven Stack

Write a menu-driven program to handle stack operations such as Push, Pop, and Display.

Solution

[Run Online]

# Question 2:
# Write a menu-driven program to perform STACK operations:
# PUSH, POP, and DISPLAY. The program should allow user to
# add elements to stack (PUSH), remove elements (POP), and
# display all current stack elements (DISPLAY).

# Program: Stack operations using Menu
STACK = []  # Creating an empty stack


# Function to add (PUSH) an element to the stack
def PUSH_element():
    item = input("Enter element to PUSH: ")  # Take input from user
    STACK.append(item)  # Add element to the end of list (top of stack)
    print(item, "Pushed into Stack")  # Confirm the operation


# Function to remove (POP) an element from the stack
def POP_element():
    if len(STACK) == 0:  # Check if stack is empty
        print("Stack Underflow! Stack is empty")  # Cannot pop from empty stack
    else:
        removed = STACK.pop()  # Remove and return last element (top of stack)
        print(removed, "Popped from Stack")  # Confirm the operation


# Function to display all elements in the stack
def DISPLAY_stack():
    if len(STACK) == 0:  # Check if stack is empty
        print("Stack is empty")  # Nothing to display
    else:
        print("Stack elements are:", STACK)  # Show all elements


# --- Main Menu ---
# Infinite loop to keep showing menu until user exits
while True:
    print("\n--- Stack Menu ---")  # Display menu header
    print("1. PUSH | 2. POP | 3. DISPLAY | 4. Exit")  # Show options
    choice = int(input("Enter your choice (1-4): "))  # Get user choice

    # Call appropriate function based on user's choice
    if choice == 1:
        PUSH_element()  # Add element to stack
    elif choice == 2:
        POP_element()  # Remove element from stack
    elif choice == 3:
        DISPLAY_stack()  # Show all elements
    elif choice == 4:
        print("Exiting Program...")  # Exit message
        break  # Exit the loop and end program
    else:
        print("Invalid choice! Please try again")  # Handle invalid input