[Tutor] how to generate random numbers in Python

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Jun 4 23:45:57 CEST 2005



On Fri, 3 Jun 2005, Xiaoxia Xu wrote:

> I tried to use a Python library module random() to generate some noise
> to my data. But the interpreter gave me an error message saying
> NameError: name 'random' is not defined.  I thought this error is
> because I don't have the pertinent library included. Could anyone tell
> me how can I get this to work?


Hi Ellen,

Can you show us what you typed in as well?  This will help us give you
better help, because then we can see exactly how you got that error.


There are several ways of getting the same error message, so we need more
context to be sure we're answering your question properly.  Otherwise, we
might respond in a way where we direct our energies toward the error
message, and not the underlying issue!


Here is a brief tutorial on using modules.  We can start by "importing" a
module.

######
>>> import random
######


This pulls in the 'random' module, one of the many Standard Library
modules described in the documentation here:

    http://www.python.org/doc/lib/



A 'module' is just some thing, a container:

######
>>> random
<module 'random' from '/usr/lib/python2.3/random.pyc'>
######


which holds a lot of useful functions and other things.  We can get a
directory listing of what's in 'random' by using dir():


######
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'Random', 'SG_MAGICCONST', 'TWOPI',
'WichmannHill', '_BuiltinMethodType', '__all__', '__builtins__',
'__doc__', '__file__', '__name__', '_acos', '_cos', '_e', '_exp',
'_floor', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test',
'_test_generator', 'betavariate', 'choice', 'cunifvariate', 'expovariate',
'gammavariate', 'gauss', 'getstate', 'jumpahead', 'lognormvariate',
'normalvariate', 'paretovariate', 'randint', 'random', 'randrange',
'sample', 'seed', 'setstate', 'shuffle', 'stdgamma', 'uniform',
'vonmisesvariate', 'weibullvariate']
######


The contents of each module usually have some associated documentation,
which we can ask by using the built-in help() function:

######
>>> help(random)
######

We can also look at the Library Reference for information:

    http://www.python.org/doc/lib/module-random.html


Within the 'random' module, we find a function called 'random'.  We use
dot notation to get at the contents of a module:

######
>>> random.random()
0.1703040598331883
######


Does this make sense so far?  Please feel free to ask more questions, and
we'll do what we can to help.

Best of wishes!



More information about the Tutor mailing list