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.

230 CHAPTER 10 ■ BATTERIES INCLUDED<br />

If you put this in a script file and run it, you get an interaction something like the following:<br />

How many dice? 3<br />

How many sides per die? 6<br />

The result is 10<br />

Creating a fortune cookie program. Assume that you have made a text file in which each line of text contains a<br />

fortune. Then you can use the fileinput module described earlier to put the fortunes in a list, and then select one<br />

randomly:<br />

# fortune.py<br />

import fileinput, random<br />

fortunes = list(fileinput.input())<br />

print random.choice(fortunes)<br />

In UNIX, you could test this on the standard dictionary file /usr/dict/words to get a random word:<br />

$ python fortune.py /usr/dict/words<br />

dodge<br />

Creating an electronic deck of cards. You want your program to deal you cards, one at a time, each time you<br />

press Enter on your keyboard. Also, you want to make sure that you don’t get the same card more than once. First,<br />

you make a “deck of cards”—a list of strings:<br />

>>> values = range(1, 11) + 'Jack Queen King'.split()<br />

>>> suits = 'diamonds clubs hearts spades'.split()<br />

>>> deck = ['%s of %s' % (v, s) for v in values for s in suits]<br />

The deck you just created isn’t very suitable for a game of cards. Let’s just peek at some of the cards:<br />

>>> from pprint import pprint<br />

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

['1 of diamonds',<br />

'1 of clubs',<br />

'1 of hearts',<br />

'1 of spades',<br />

'2 of diamonds',<br />

'2 of clubs',<br />

'2 of hearts',<br />

'2 of spades',<br />

'3 of diamonds',<br />

'3 of clubs',<br />

'3 of hearts',<br />

'3 of spades']<br />

A bit too ordered, isn’t it? That’s easy to fix:

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

Saved successfully!

Ooh no, something went wrong!