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.

Lines 1943<br />

The entire menu-driven application is controlled from the showmenu() function. Here, the user is<br />

prompted with the menu options. Once the user makes a valid choice, the proper function is called. We<br />

have not covered exceptions and try-except statement in detail yet, but basically that section of the<br />

code allows a user to type ^D (EOF, which generates an EOFError) or ^C (interrupt to quit, which<br />

generates a KeyboardInterrupt error), both of which will be processed by our script in the same manner<br />

as if the user had typed the 'q' to quit the application. This is one place where the exception-handling<br />

feature of <strong>Python</strong> comes in extremely handy. The outer while loop lets the user continue to execute<br />

commands until they quit the application while the inner one prompts the user until they enter a valid<br />

command option.<br />

Lines 4546<br />

This part of the code starts up the program if invoked directly. If this script were imported as a module,<br />

only the functions and variables would have been defined, but the menu would not show up. For more<br />

information regarding line 45 and the __name__ variable, see Section 3.4.1.<br />

Here is a sample execution of our script:<br />

$ stack.py<br />

p(U)sh<br />

p(O)p<br />

(V)iew<br />

(Q)uit<br />

Enter choice: u<br />

You picked: [u]<br />

Enter new string: <strong>Python</strong><br />

p(U)sh<br />

p(O)p<br />

(V)iew<br />

(Q)uit<br />

Enter choice: u<br />

You picked: [u]<br />

Enter new string: is<br />

p(U)sh<br />

p(O)p<br />

(V)iew<br />

(Q)uit<br />

Enter choice: u<br />

You picked: [u]<br />

Enter new string: cool!<br />

p(U)sh<br />

p(O)p<br />

(V)iew

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

Saved successfully!

Ooh no, something went wrong!