[Tutor] Help with pi and the math module.

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Sep 24 01:21:50 CEST 2005



On Fri, 23 Sep 2005, Nathan Pinno wrote:

> I need help with pi and the math module. I had import math at the top of
> a program, but when it came to diameter*pi, it said that pi was not
> defined.


Hi Nathan,


Python's module import will not automatically pull all the names in a
module and dump them into our world: they'll be held within the module,
accessible but still boxed up.


Let's take another example, like the 'random' module:

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


If we're doing something like:

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

then to access the random() function that lives in the random module, we
say:

######
>>> random.random()
0.64082684341957585
######


If we just say 'random', we're talking about the random module, not the
random function:

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

which itself does have a few things in its internals:

######
>>> 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']
######


Does this clarify things for you?


For more information on this, see a tutorial like Alan Gauld's "How to
Program":

    http://www.freenetpages.co.uk/hp/alan.gauld/tutfunc.htm

or any of the other tutorials in:

    http://wiki.python.org/moin/BeginnersGuide/NonProgrammers



More information about the Tutor mailing list