16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 10 ■ BATTERIES INCLUDED 231<br />

>>> from random import shuffle<br />

>>> shuffle(deck)<br />

>>> pprint(deck[:12])<br />

['3 of spades',<br />

'2 of diamonds',<br />

'5 of diamonds',<br />

'6 of spades',<br />

'8 of diamonds',<br />

'1 of clubs',<br />

'5 of hearts',<br />

'Queen of diamonds',<br />

'Queen of hearts',<br />

'King of hearts',<br />

'Jack of diamonds',<br />

'Queen of clubs']<br />

Note that I’ve just printed the 12 first cards here, <strong>to</strong> save some space. Feel free <strong>to</strong> take a look at the whole deck<br />

yourself.<br />

Finally, <strong>to</strong> get <strong>Python</strong> <strong>to</strong> deal you a card each time you press Enter on your keyboard, until there are no more cards,<br />

you simply create a little while loop. Assuming that you put the code needed <strong>to</strong> create the deck in<strong>to</strong> a program file,<br />

you could simply add the following at the end:<br />

while deck: raw_input(deck.pop())<br />

■Note If you try the while loop shown here in the interactive interpreter, you’ll notice that an empty string<br />

gets printed out every time you press Enter because raw_input returns what you write (which is nothing),<br />

and that will get printed. In a normal program, this return value from raw_input is simply ignored. To have<br />

it “ignored” interactively, <strong>to</strong>o, just assign the result of raw_input <strong>to</strong> some variable you won’t look at again<br />

and name it something like ignore.<br />

shelve<br />

In the next chapter, you learn how <strong>to</strong> s<strong>to</strong>re data in files, but if you want a really simple s<strong>to</strong>rage<br />

solution, the shelve module can do most of the work for you. All you have <strong>to</strong> do is supply it with<br />

a file name. The only function of interest in shelve is open. When called (with a file name) it<br />

returns a Shelf object, which you can use <strong>to</strong> s<strong>to</strong>re things. Just treat it as a normal dictionary<br />

(except that the keys must be strings), and when you’re done (and want things saved <strong>to</strong> disk)<br />

you call its close method.<br />

A Potential Trap<br />

It is important <strong>to</strong> realize that the object returned by shelve.open is not an ordinary mapping, as<br />

the following example demonstrates:

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

Saved successfully!

Ooh no, something went wrong!