CHAPTER 10 (Affordable web design) BATTERIES INCLUDED 231 >>> from
CHAPTER 10 BATTERIES INCLUDED 231 >>> from random import shuffle >>> shuffle(deck) >>> pprint(deck[:12]) [’3 of spades’, ‘2 of diamonds’, ‘5 of diamonds’, ‘6 of spades’, ‘8 of diamonds’, ‘1 of clubs’, ‘5 of hearts’, ‘Queen of diamonds’, ‘Queen of hearts’, ‘King of hearts’, ‘Jack of diamonds’, ‘Queen of clubs’] 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 yourself. Finally, to get Python to deal you a card each time you press Enter on your keyboard, until there are no more cards, you simply create a little while loop. Assuming that you put the code needed to create the deck into a program file, you could simply add the following at the end: while deck: raw_input(deck.pop()) Note If you try the while loop shown here in the interactive interpreter, you ll notice that an empty string gets printed out every time you press Enter because raw_input returns what you write (which is nothing), and that will get printed. In a normal program, this return value from raw_input is simply ignored. To have it ignored interactively, too, just assign the result of raw_input to some variable you won t look at again and name it something like ignore. shelve In the next chapter, you learn how to store data in files, but if you want a really simple storage solution, the shelve module can do most of the work for you. All you have to do is supply it with a file name. The only function of interest in shelve is open. When called (with a file name) it returns a Shelf object, which you can use to store things. Just treat it as a normal dictionary (except that the keys must be strings), and when you re done (and want things saved to disk) you call its close method. A Potential Trap It is important to realize that the object returned by shelve.openis not an ordinary mapping, as the following example demonstrates:
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.