Page 328 - Beginning Programming with Pyth - John Paul Mueller
P. 328
FIGURE 14-11: After displaying your selection, the application displays the menu again. Creating Stacks Using Lists
A stack is a handy programming structure because you can use it to save an application execution environment (the state of variables and other attributes of the application environment at any given time) or as a means of determining an order of execution. Unfortunately, Python doesn’t provide a stack as a collection. However, it does provide lists, and you can use a list as a perfectly acceptable stack. The following steps help you create an example of using a list as a stack.
1. Type the following code into the notebook — pressing Enter after
each line:
MyStack = []
StackSize = 3
def DisplayStack():
print("Stack currently contains:")
for Item in MyStack:
print(Item)
def Push(Value):
if len(MyStack) < StackSize: MyStack.append(Value)
else:
print("Stack is full!")
def Pop():
if len(MyStack) > 0:
MyStack.pop() else:
print("Stack is empty.") Push(1)