Hardware Reference
In-Depth Information
he Python random , module contains the function random.randint
(startNumber, endNumber) which is used to generate a random number between
two specific numbers ( startNumber , endNumber ).
The following code will print a random number between 1 and 10 each time it is run.
If you want to see the results, you should create a new python program:
import random
randomNo = random.randint(1,10)
print randomNo
By adding an if statement to check when the random number is 10, you create a prob-
ability check that will be true in approximately 1 time in every 10:
import random
if random.randint(1,10) == 10:
print "This happens about 1 time in 10"
else
print "This happens about 9 times out of 10"
If you were to run the program above 100 times you would expect to see “This happens
about 1 time in 10” printed about 10 times (see Figure 8-3), but you might only see it
9 or 11 times, or maybe even not at all. Its unpredictable!
If you were to run this program 100 times, how many times would you expect to see
“This happens about 1 time in 10” printed? You would expect to see it 10 times, but
you might not, you might not see it all, or you might see it 100 times!
If you use random numbers and a probability check in your block friend program, you
can make it less predictable. You can even make the block friend “unfriend” your player!
Add some new rules to the block friend program so that if the block friend is “sad”
there is a 1 in 100 chance she will decide she has had enough of waiting and will not
follow your player if he comes back and gives her a hug:
1. Open IDLE and open the BlockFriend.py program from the MyAdventures
folder.
2. Click File Save As and save the file as BlockFriendRandom.py .
Search WWH ::




Custom Search