python-模拟栈操作(47)

#转自https://www.jianshu.com/c/00c61372c46a网址
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()

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值