[Tutor] Is this code right?

Michael P. Reilly arcege@shore.net
Thu, 30 Mar 2000 18:38:44 -0500 (EST)


> I was wondering if this code is right i ran idle's debug on it and no errors 
> came up but i cant seem to use the function when i import the module it is 
> in. The function is meant to create a list of random numbers, im new at this 
> so i dont know if i'm doing something wrong. Any help is greatly 
> apprietiated. I'm running Win 98 and Python 1.5.2.
> 
> import whrandom
> 
> def rand_strng(x, y, z):
>     while x > 0:
>         w = randint(y, z)
>         list[x] = w
>         x = x - 1
>         return x
>     return list

The "randint" function is in the whrandom function, not this module (or
in the __builtin__ module).  You will want to either
a) change "import whrandom" to "from whrandom import randint"; or
b) reference the randint() function expicitly as
   "w = whrandom.randint(y, z)".

Also, you do not define the variable "list" in your function.  Unless it
is a global variable (of a mutable sequence of at least `x' elements, or
a mapping), then you will get an error there.  You probably do not want
to use the name "list" either since it is the same name as the built-in
function.

How about:
from whrandom import randint

def rand_strng(x, y, z):
  list = [0] * x
  while x > 0:
    w = randint(y, z)
    list[x] = w
    x = x - 1
  return list

(I noticed that you have `return x' inside the while loop, before the
`return list', I assume that's a mistake and removed it.)

Hope this helps,
  -Arcege

PS, the source documentation for whrandom says that you should use
randrange instead of randint.  No real harm, but randint might be
removed in a future release.

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------