0

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

1

1 Answer 1

1

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! []
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.