我正在嘗試實現基本的堆棧操作。問題是我需要循環繼續要求輸入選擇并想繼續執行直到我輸入 1、2、3 以外的數字。當我運行這段代碼時,在輸入選項 1 后,它會一次又一次地調用 if 語句。我希望 if 語句在調用函數一次后停止,直到我再次調用它。我知道代碼有些混亂,我只想要堆棧操作的基本實現。def create_stack(): stack = [] return stackdef check_empty(stack): return len(stack) == 0def 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 Falsestack = []stack_op()
1 回答

守候你守候我
TA貢獻1802條經驗 獲得超10個贊
第二個while
循環是不必要的,它重復運行相同的 if 塊而不要求新的輸入。
只需刪除整個while choice < 4:
語句并縮進下面的 if 塊。然后,它起作用了。break
或者,您可以在每個 if 和 elif 命令塊中包含一個,以在處理輸入后終止不必要的 while 循環。
添加回答
舉報
0/150
提交
取消