Re: [Tutor] Generating random in a user specified range.

Magnus Lycka magnus at thinkware.se
Tue Apr 27 12:32:29 EDT 2004


Adam wrote:
> However, I seem to have a problem - I get an error using 
> random.randint(a,b) and with random.randrange(a,b). 

It's *much* easier to help you if you tell us exactly the error 
messages you get. Can't you copy the traceback directly to the mail?

Btw, used with two integers as arguments, random.randint(x,y) is
exactly the same thing as random.randrange(x,y+1). You can expect
them to behave fairly similarly from an error point of view, but
note that your "top" value will never be returned from 
randrange(bottom, top). See below:

>>> import random
>>> random.randint(1,1)
1
>>> random.randrange(1,2)
1
>>> random.randrange(1,1)

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in -toplevel-
    random.randrange(1,1)
  File "D:\Python23\lib\random.py", line 171, in randrange
    raise ValueError, "empty range for randrange()"
ValueError: empty range for randrange()

> It seems that it 
> might be fussy accepting parts of a list as the argument. I've tried 

If "x = [5, 20]", then x[0] and x[1] are integers, not "parts of a list",
so this isn't your problem.

>>> x = [5, 20]
>>> random.randint(x[0], x[1])
15
>>> random.randrange(x[0], x[1])
14

No problems!

> converting them to integers and then passing the interger, but it still 
> complains.

You *should* provide integers as parameters with random.randrange().
Never strings. 

Python is not a toy language that tries to guess what the programmer 
meant and corrects him silently when he made a mistake. In the long 
run, the Python tenet: "In the face of ambiguity, refuse the temptation 
to guess" is very helpful when we try to build robust applications.

> range = range() 

I assume you have this *after* your function definition in your actual
program, otherwise it will not call your not yet defined function, but
rather to the standard built in Python function called range. E.g.

Traceback (most recent call last):
  File "C:/TEMP/temp.py", line 1, in -toplevel-
    range = range()
TypeError: range expected at least 1 arguments, got 0

> def range():

As I said, range is the name of a builtin function. It's not a good idea 
to hide builtin functions with user defined ones.

If I take your code, add "import random" at the top, and move the
initial lines to the end of the program, after the functions, it works
as expected, with no errors. (Well, I guess you actually want randint
rather than randrange as explained above.)

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list