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.

39 try:<br />

40 choice =<br />

raw_input(prompt).strip()[0].lower()<br />

41 except (EOFError, KeyboardInterrupt):<br />

42 choice = 'q'<br />

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

44 if choice not in 'neq':<br />

45 print 'invalid option, try again'<br />

46 else:<br />

47 chosen = True<br />

48<br />

49 if choice == 'q': done = True<br />

50 if choice == 'n': newuser()<br />

51 if choice == 'e': olduser()<br />

52<br />

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

54 showmenu()<br />

Line-by-Line Explanation<br />

Lines 13<br />

After the Unix-startup line, we initialize the program with an empty user database. Because we are not<br />

storing the data anywhere, a new user database is created every time this program is executed.<br />

Lines 515<br />

The newuser() function is the code that serves new users. It checks to see if a name has already been<br />

taken, and once a new name is verified, the user is prompted for his or her password (no encryption<br />

exists in our simple program), and his or her password is stored in the dictionary with his or her user<br />

name as the key.<br />

Lines 1724<br />

The olduser() function handles returning users. If a user returns with the correct login and password, a<br />

welcome message is issued. Otherwise, the user is notified of an invalid login and returned to the menu.<br />

We do not want an infinite loop here to prompt for the correct password because the user may have<br />

inadvertently entered the incorrect menu option.<br />

Lines 2651<br />

The real controller of this script is the showmenu() function. The user is presented with a friendly menu.<br />

The prompt string is given using triple quotes because it takes place over multiple lines and is easier to<br />

manage on multiple lines than on a single line with embedded '\n' symbols. Once the menu is<br />

displayed, it waits for valid input from the user and chooses which mode of operation to follow based on<br />

the menu choice. The try-except statements we describe here are the same as for the stack.py and<br />

queue.py examples from the last chapter (see Section 6.14.1).<br />

Lines 5354

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

Saved successfully!

Ooh no, something went wrong!