#!/usr/bin/env python #定義一個列表來模擬棧 stack = [] #進棧,調(diào)用列表的append()函數(shù)加到列表的末尾,strip()沒有參數(shù)是去掉首尾的空格 def pushit(): stack.append(raw_input('Enter new string: ').strip()) #出棧,用到了pop()函數(shù) def popit(): if len(stack) == 0: print 'Cannot pop from an empty stack!' else: print 'Removed [', stack.pop(), ']' #編歷棧 def viewstack(): print stack #CMDs是字典的使用 CMDs = {'u': pushit, 'o': popit, 'v': viewstack} #pr為提示字符 def showmenu(): pr = """ p(U)sh p(O)p (V)iew (Q)uit Enter choice: """ while True: while True: try: #先用strip()去掉空格,再把第一個字符轉(zhuǎn)換成小寫的 choice = raw_input(pr).strip()[0].lower() except (EOFError, KeyboardInterrupt, IndexError): choice = 'q' print ' You picked: [%s]' % choice if choice not in 'uovq': print 'Invalid option, try again' else: break #CMDs[]根據(jù)輸入的choice從字典中對應(yīng)相應(yīng)的value,比如說輸入u,從字典中得到value為pushit,執(zhí)行pushit()進棧操作 if choice == 'q': break CMDs[choice]() #判斷是否是從本文件進入,而不是被調(diào)用 if __name__ == '__main__': showmenu()
希望本文所述對大家的Python程序設(shè)計有所幫助。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com