[Tutor] Need help with random numbers

Wesley Chun wesc@deirdre.org
Mon, 16 Jul 2001 22:41:28 -0700 (PDT)


On Mon, 16 Jul 2001 steve@purestfeeling.net wrote:
>
> I need to generate a random integer within certain bounds, say 1-10, and
> feed it into a variable for use elsewhere in the program, so A= the
> generated number.


you want the 'random' module.  it's got the following useful functions:

randint(a, b):  takes two integer values and returns a random integer
between those values inclusive, i.e., a <= N <= b

uniform(a, b):  does almost the same thing as randint(), but returns a
float and is inclusive only of the smaller number (exclusive of the larger
number), i.e. a <= N < b

random():  works just like uniform() except that the smaller number is
fixed at 0.0, and the larger number is fixed at 1.0, i.e., 0.0 <= N < 1.0

choice(seq):  given a sequence, randomly selects and returns a sequence
item

randrange([start,] stop[, step]): obsoletes randint() in 2.0.  Return a
randomly selected element from range(start, stop, step). This is
equivalent to choice(range(start, stop, step)); recall that range(a, b)
counts from a to (b-1), so randrange(a, b) returns an integer inclusive of
a but exclusive of b, i.e. a <= N < b

- - - - - - - - - - - - - - - - - - - -
here's an example using random.randrange() and numbers b/w 1 and 10:

>>> import random
>>> for i in range(20):
	print random.randrange(1, 11),


6 8 8 1 9 10 7 3 6 1 3 1 6 7 4 2 7 7 7 3
>>>
>>> for i in range(20):
	print random.randrange(1, 11),


5 9 6 8 3 3 9 10 4 9 9 9 3 10 9 1 7 4 7 5
>>>

More information on random numbers is available in Section 5.7 in Core
Python Programming on pp. 123-24.

hope this helps!

-wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Silicon Valley-SF Bay Area Python users group:  http://baypiggies.org

"Core Python Programming", Prentice Hall PTR, December 2000
    http://starship.python.net/crew/wesc/cpp/

wesley.j.chun :: wesc@baypiggies.org
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/