04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

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

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

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, to save some space. Feel free to take a look at the whole deck<br />

yourself.<br />

Finally, to get Python to 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 to create the deck into 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, too, just assign the result of raw_input to 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 to store data in files, but if you want a really simple storage<br />

solution, the shelve module can do most of the work for you. All you have to 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 to store 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 to disk)<br />

you call its close method.<br />

A Potential Trap<br />

It is important to 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!