Python 中的堆栈操作

Stack Operation in Python

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

问题是我需要循环继续要求输入选择并希望继续执行直到我输入 1、2、3 以外的数字。 当i运行这段代码,输入选项1后,反复调用if语句。我希望 if 语句在调用函数一次后停止,直到我调用它 again.I 知道代码有点乱,我只想要堆栈操作的基本实现。

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-block 而不要求新的输入。

只需删除整个 while choice < 4: 语句并缩进下面的 if-block。然后,它起作用了。或者,您可以在每个 if-and elif-command 块中包含一个 break 以在处理输入后终止不必要的 while-loop。