Random Python

From OpenCircuits
Jump to navigation Jump to search

Overview[edit]

Sometimes, for example if you wanted to simulate throwing a die, it is useful for the computer to generate random numbers. There are, as usual, a ton of ways to do this, but here we will keep it simple. If you want more complexity ( or perhaps more detail than this page ) use the links below. Please copy the code into your environment and run it.



A Simple Example[edit]

All these do the same thing with slight different styles, the first A works but is poor style for sure.

For any of this code to work you have to have this statement first:

import random   # this gives you access to the random "library"

Here is the first simple, but not good style code. Should be easy to understand.

print "randrange 1 to 11 gives numbers including 1 to 10 -- run it 10 times A"

print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )   # two items are printed just separate by a comma
print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )   # the first item printed is a literal
print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )   # the second item is a call to the random function 
print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )
print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )
print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )
print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )
print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )
print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )
print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )

When code is repeated it is better style code to put it in a loop ( and perhaps define a function, something we will not do here ).

print "randrange 1 to 11 gives numbers including 1 to 10 -- run it 10 times B"
for ix in range( 0, 10 ):
     print "randrange( 1, 11, ) : ", random.randrange( 1, 11, )

This code is slightly different by putting the random value in a variable before printing it.


print "randrange 1 to 11 gives numbers including 1 to 10 -- run it 10 times C"
for ix in range( 0, 10 ):
     random_number  = random.randrange( 1, 11, )
     print "randrange( 1, 11, ) : ", random_number

Links[edit]