Code about stacks in Python doesnt print anything. why?

I have an assignment where the teacher gave me the code ready but i have to run it and figure out what it does and why. The code doesnt run in pycharm can you help me find any mistakes ???

I tried putting every line in its place to avoid errors but it just doent print anything. Does it need another class or something like that ?

def push(elements):
    if len(stack)>=limit:
        print('Stack Overflow!')
    else:
        stack.append(elements)
        print('Stack after Push',stack)
        def pop():
            if len(stack)<=0:
                print('Stack Underflow!')
                return0
            else:
                return stack.pop() 
        stack = []
contents, elements = 0, 0
limit = int(input('Enter the no of elements to be stored in stack:'))
for contents in range(limit):
    elements = int(input('Enter elements' + str(contents) + ':'))
    push(elements)
for contents in range(limit):
    print('Popping' + str(limit - contents) + 'th element:', pop())
    print('Stack after Popping!', stack)

I really cant tell why it doesnt print anything

Upvotes: 0

Views: 32

Answers (1)

depperm
depperm

Reputation: 10746

I believe your indentation is wrong. I believe the code should be:

def push(elements):
    if len(stack)>=limit:
        print('Stack Overflow!')
    else:
        stack.append(elements)
        print('Stack after Push',stack)
def pop(): # unindent this function
    if len(stack)<=0:
        print('Stack Underflow!')
        return0
    else:
        return stack.pop() 
stack = [] # unindent
contents, elements = 0, 0
limit = int(input('Enter the no of elements to be stored in stack:'))
for contents in range(limit):
    elements = int(input('Enter elements' + str(contents) + ':'))
    push(elements)
for contents in range(limit):
    print('Popping' + str(limit - contents) + 'th element:', pop())
    print('Stack after Popping!', stack)

Then the output is:

Enter the no of elements to be stored in stack:3
Enter elements0:1
Stack after Push [1]
Enter elements1:2
Stack after Push [1, 2]
Enter elements2:3
Stack after Push [1, 2, 3]
Popping3th element: 3
Stack after Popping! [1, 2]
Popping2th element: 2
Stack after Popping! [1]
Popping1th element: 1
Stack after Popping! []

Upvotes: 1

Related Questions