现在的位置: 首页 > 综合 > 正文

python 学习笔记

2014年02月07日 ⁄ 综合 ⁄ 共 836字 ⁄ 字号 评论关闭

用列表模拟堆栈(stack.py)

#!/usr/bin/env python

stack=[]

def pushit():
   stack.append(raw_input('Enter new string:').strip())

def popit():
   if len(stack) == 0:
      print 'Can not pop from an empty stack'
   else:
      print 'Removed [', `stack.pop()`, ' ]'


def viewstack():
   print stack

CMDs={'u':pushit, 'o':popit, 'v':viewstack}

def showmenu():
  pr= '''
  p(u)sh
  p(O)p
  (V)iew
  (Q)uit
  Enter choice:'''
  while True:
     while True:
        try:
           choice=raw_input(pr).strip()[0].lower()
        except (EOFError, KeyboardInterrupt, IndexError):
           choice='q'
        print '\nyou picked: [%s]' % choice
        if choice not in 'uovq':
           print 'Invalid option try again!'
        else: 
           break

     if choice=='q':
        break
     CMDs[choice]()
if __name__=='__main__':
   showmenu()

书上的代码缩进不是很清楚的
stack是一个列表
(‵‵)操作符是返回一个对象的字符串表示
使用列表的append()方法和pop()方法来实现堆栈的进栈和出栈操作
try except中间放置的是异常处理的测试代码
关于if __name__=='__main__':
这里模块是对象,并且每个模块都有一个内置属性__name__ ,其值取决于如何应用模块
如果直接运行该模块__name__值就是__main__
从其他模块import该模块的话,这时__name__ 名就是模块的文件名

抱歉!评论已关闭.