Home > Software design >  How to take user input 'XXX' to end?
How to take user input 'XXX' to end?

Time:10-03

stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')

What should I do to take input like this?

  • Enter element, 'XXX' to end: a
  • Enter element, 'XXX' to end: b
  • Enter element, 'XXX' to end: c
  • Enter element, 'XXX' to end: XXX

CodePudding user response:

From what I understood, you want to take user input and append it to a stack.

You can use list for this as mentioned below:

stack = []
elem = input("Enter element, 'XXX' to end:")

while elem != 'XXX':
    stack.append(elem)
    elem = input("Enter element, 'XXX' to end:")

Alternatively, you can also use collections.deque which is more efficient than list.

from collections import deque

stack = deque()
elem = input("Enter element, 'XXX' to end:")

while elem != 'XXX':
    stack.append(elem)
    elem = input("Enter element, 'XXX' to end:")

To pop elements, simply use stack.pop() which would remove the last inserted element from list or deque.

  • Related