15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

28 while True:<br />

29 while True:<br />

30 try:<br />

31 choice = raw_input(pr).strip()[0].lower()<br />

32 except (EOFError,KeyboardInterrupt,IndexError):<br />

33 choice = 'q'<br />

34<br />

35 print '\nYou picked: [%s]' % choice<br />

36 if choice not in 'uovq':<br />

37 print 'Invalid option, try again'<br />

38 else:<br />

39 break<br />

40<br />

41 if choice == 'q':<br />

42 break<br />

43 CMDs[choice]()<br />

44<br />

45 if __name__ == '__main__':<br />

46 showmenu()<br />

Line-by-Line Explanation<br />

Lines 13<br />

In addition to the Unix startup line, we take this opportunity to clear the stack (a list).<br />

Lines 56<br />

The pushit() function adds an element (a string prompted from the user) to the stack.<br />

Lines 812<br />

The popit() function removes an element from the stack (the more recent one). An error occurs when<br />

trying to remove an element from an empty stack. In this case, a warning is sent back to the user.<br />

When an object is popped from the stack, the user sees which element was removed. We use single<br />

backquotes or backticks ( ' ) to symbolize the repr() command, showing the string complete with<br />

quotes, not just the contents of the string.<br />

Lines 1415<br />

The viewstack() function displays the current contents of the stack.<br />

Line 17<br />

Although we cover dictionaries formally in the next chapter, we wanted to give you a really small<br />

example of one here, a command vector (CMDs). The contents of the dictionary are the three "action"<br />

functions defined above, and they are accessed through the letter that the user must type to execute<br />

that command. For example, to push a string onto the stack, the user must enter 'u', so 'u' is how<br />

access the pushit() from the dictionary. The chosen function is then executed on line 43.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!