CBSE Class 12 Computer Science Question 23 of 43

Practice Paper — Question 5

Back to all questions
5
Question

Question 20

Write push(rollno) and pop() method in Python:

push(rollno) — to add roll number in Stack

pop() — to remove roll number from Stack

Solution
stack = []

def push(rollno):
    stack.append(rollno)
    print("Roll number", rollno, "added to the stack.")

def pop():
    if not is_empty():
        rollno = stack.pop()
        print("Roll number", rollno, "removed from the stack.")
    else:
        print("Stack is empty, cannot perform pop operation.")

def is_empty():
    return len(stack) == 0

push(11)
push(12)
push(13)

pop()
pop()
Output
Roll number 11 added to the stack.
Roll number 12 added to the stack.
Roll number 13 added to the stack.
Roll number 13 removed from the stack.
Roll number 12 removed from the stack.
Answer