[Tutor] The Game of Life question

Brian van den Broek bvande at po-box.mcgill.ca
Wed Jan 5 16:42:52 CET 2005


Kooser, Ara S said unto the world upon 2005-01-05 10:15:
>    This is most likely a silly question and me not understanding python
> enough. I am a mentor for some high school kids participating in a
> supercomputing challenge. My background in programming is F77 (yeah
> laugh it up) and I want the kids to learn python and use it for the
> challenge. 
>    They picked a project to model the flow of smallpox in a city and
> surroundings areas. So I saw the game of life and thought maybe they
> could modify it for use as a smallpox model. My question is when I run
> this code as is and execute the command to generate a world, I get the
> following error:
> 
> Traceback (most recent call last):
>   File "<pyshell#0>", line 1, in -toplevel-
>     print_world(make_random_world(10, 10))
>   File "C:\Python23\gameoflife.py", line 12, in make_random_world
>     world[i, j] = random.choice([LIVE, DEAD])
> NameError: global name 'random' is not defined
> 
> 
> Does "random" need to be defined after LIVE,DEAD or am I just missing
> something. I was trying to run this on my work computer which is a winXP
> machine running python 2.4.
> 
> Thanks,
> Ara

<SNIP>

Hi Ara,

Not an expert, but from the traceback, my guess is that you've not 
included the line

import random

in your script before the call to random.choice.

Random and other modules need to be imported before they can be used. 
You can think of import loosely as doing two things:
1) adding a module to the available command set, and
2) running whatever top level code is contained in the module.

There is a fairly strong convention to put all imports near the 
beginning of a module (usually after the module docstring and any legal 
kung-fu).

Does that clear it up?

Best,

Brian vdB


More information about the Tutor mailing list