Python模拟入栈出栈操作

目标:

  1.编写菜单,提示用户操作选项(push,pop,view,quit)

  2.规则:定义列表,先入栈,后出栈,后入栈,先出栈

1.模拟入栈、出栈操作

>>> list1 = []
>>> list1.append('a')
>>> list1
['a']
>>> list1.append('b')
>>> list1
['a', 'b']
>>> list1.pop()
'b'
>>> list1
['a']
>>> list1.pop()
'a'
>>> list1
[]
>>>

 

2.编写实现模拟入栈、出栈以及查询等功能

[root@localhost python]# cat in_stack_out.py
#!/usr/bin/env python
#coding:utf8

db = []

#定义入栈函数
def push_it(): item = raw_input("item: ") db.append(item)
#定义出栈函数
def pop_it(): if db: print "Poped item is:", db.pop() else: print "\033[31;1m%s\033[0m" % ('列表为空,请选择其他选项') #定义查询函数 def view_it(): print "\033[32;1m%s\033[0m" % db
#定义函数功能的提示菜单
def show_menu(): cmds = { "0": push_it, "1": pop_it, "2": view_it } prompt = '''(0) push (1) pop (2) view (3) quit Please input your choice(0/1/2/3): ''' while True: choice = raw_input(prompt).strip()[0] if choice not in '0123': print "Invalid choice, Try Again!" continue if choice == '3': break cmds[choice]() if __name__ == "__main__": show_menu()

 

3.运行代码,测试效果

转载于:https://www.cnblogs.com/xkops/p/6244487.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值