Python中的堆栈操作

问题描述

我正在尝试实现基本的堆栈操作。

问题是我需要循环以继续要求输入选择并希望继续执行直到我输入1,2,3以外的数字。 当我运行此代码时,输​​入选择1后,它将一次又一次地调用if语句。我希望if语句在调用一次函数后停止,直到我再次调用它。我知道代码有些混乱,我只希望堆栈操作的基本实现。

def create_stack():
    stack = []
    return stack

def check_empty(stack):
    return len(stack) == 0

def push(stack,item):
    stack.append(item)
    print("Item pushed")

def pop(stack):
    if check_empty(stack):
        return "Stack is empty"
    return stack.pop()


def display(stack):
    for i in stack:
        print(i,end = ' ')


def stack_op():
    while True:
        choice = int(input("Enter the choice "))
        while choice < 4:
            if choice == 1:
                item = int(input("Enter the item :"))
                push(stack,item)
            elif choice == 2:
                pop(stack)
            elif choice == 3:
                display(stack)  
            else:
                break
    return False

stack = []
stack_op()

解决方法

第二个while循环是不必要的,并重复运行相同的if块而不要求新输入。

只需删除整个while choice < 4:语句并确定下面的if块即可。然后,它起作用。另外,您可以在每个if-和elif命令块中包含一个break,以在处理完输入后终止不必要的while循环。