Python中有关堆栈的代码不会输出任何内容。为什么?

时间:2019-05-29 15:24:38

标签: python list stack new-operator

我有一个作业,老师给了我准备好的代码,但是我必须运行它并弄清楚它的作用和原因。该代码未在pycharm中运行,您能帮我发现任何错误吗?

我尝试将每一行都放在适当的位置以避免错误,但是它确实可以打印任何内容。是否需要其他课程或类似的课程?

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)

我真的不知道为什么它什么都不打印

1 个答案:

答案 0 :(得分:1)

我相信您的缩进是错误的。我相信代码应该是:

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)

然后输出为:

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! []