CBSE Class 12 Computer Science
Question 48 of 63
Data Structures in Python — Question 22
Back to all questions 22
Question Write a program that, depending upon the user's choice, either pushes or pops an element in a Stack. The elements are shifted towards the right so that the top always remains at 0th (zeroth) index.
def push(stack, element):
stack.insert(0, element)
def pop(stack):
if stack == []:
print("Stack is empty")
else:
print("Popped element:", stack.pop(0))
stack = []
while True:
print("STACK OPERATIONS")
print("1. Push element")
print("2. Pop element")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
element = input("Enter the element to push: ")
push(stack, element)
elif choice == '2':
pop(stack)
elif choice == '3':
print("Exiting program")
break
else:
print("Invalid choice. Please enter a valid option.")STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 3
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 6
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 9
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 1
Enter the element to push: 12
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 2
Popped element: 12
STACK OPERATIONS
1. Push element
2. Pop element
3. Exit
Enter your choice (1-3): 3
Exiting program