1. 程式人生 > >python-模擬棧操作(47)

python-模擬棧操作(47)

stack = []

def push_it():  #向棧裡面放
    item = input('item to push: ')
    stack.append(item)

def pop_it():   #彈出
    if stack:
        print("from stack popped %s" % stack.pop())

def view_it():  #查詢
    print(stack)

def show_menu():
    cmds = {'0':push_it,'1':pop_it,'2':view_it} #將上面的函式放入字典
    prompt = """(0) push it
(1) pop it
(2) view it
(3) exit
Please input your choice(0/1/2/3): """
    while True:
        choice = input(prompt).strip()[0]   # input()得到字串,用strip()去除兩端空白,再取下標為0的字元
        if choice not in '0123':
            print('Invalid input. Try again.')
            continue

        if choice == '3':
            break

        cmds[choice]()  #執行上面定義的函式

if __name__ == '__main__':
    show_menu()