[Tutor] Generating small random integer

Alan Gauld alan.gauld at freenet.co.uk
Mon Feb 20 02:07:44 CET 2006


> Traceback (most recent call last):
>  File "<pyshell#50>", line 1, in -toplevel-
>    factor0(3737)
>  File "<pyshell#35>", line 12, in factor0
>    v = transfac(v)
>  File "<pyshell#48>", line 19, in transfac
>    na = na + randint(1,na)
> NameError: global name 'randint' is not defined
 
Reading from the bottom uip it tells us that randint is not defined.
randint is in the random module.

> def transfac(v):
>   import random
>   a = v[0]
>  randint(a, b)

You need to prepend the function name with the module 
name - this prevents "name collisions" across modules.

ie

   random.randint(a,b)

> I found this, but it doesn't tell me how to use it.

Having found your function (import the module if necessary) 
then use help()

>>> import math
>>> help(math)
>>> help(math.sqrt)

Note when using help() do not put parens after the required
function name - that would ask for help on the returned value!
Use 'Q' to exit the help screen. Use 'b' to reverse up a screeen

BTW there is a built in pow which is slightly different to the 
one in the math module...

Tip: You can also use dir() to find out the names of functions 
in a module, including the built in functions:

 dir(__builtins__)
dir(math)

Note 2 underscores each side of builtins coz its a 'magic' name, 
imported modules are named as usual...

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list