[Tutor] Generating random in a user specified range.

Crabtree, Chad Chad.Crabtree at nationalcity.com
Tue Apr 27 12:16:24 EDT 2004

> However, I seem to have a problem - I get an error using 
> random.randint(a,b) and with random.randrange(a,b). It seems that it 
> might be fussy accepting parts of a list as the argument. I've tried 
> converting them to integers and then passing the interger, 
> but it still 
> complains.
> Any advice on what I can do to fix this?
> Thanks.
> The driving code is:
> range = range()
> print range
> raw_input("click ok to carry ok")
> target = generatenumber(range) #kicks the whole thing off

 You will hear this several times range is a built in function when you
assign to it you erase this function.  This in practice is a bad thing.
> def range():
> 	strtop = raw_input("What is your top number?")
> 	strbottom = raw_input("What is your bottom number?")
> 	top = int(strtop)
> 	bottom = int(strbottom)
> 	range = [bottom, top]
> 	print "range top is ", range[0]
> 	print "range bottom is ", range[1]
> 	return range

you need to strip the stuff from this.  I would do it thus.  
import string

this gets ride of any string whitespace strangeness that canot be converted
to an integer.

> def generatenumber(range):
>      top = int (range[0])
>      bottom = int (range[1])
>      target = random.randrange(range[1], range[0]) # and I've 
> also tried 
> (bottom,top)
>      print "Target is ", target
>      ok = raw_input("please press enter to continue")
>      return target
with random.randrange(x,y) x must be smaller than y if not range will act

>>> random.choice(range(10,1))

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in -toplevel-
  File "c:\python\lib\random.py", line 231, in choice
    return seq[int(self.random() * len(seq))]
IndexError: list index out of range
>>> range(10,1)
>>> range(10,1,-1)
[10, 9, 8, 7, 6, 5, 4, 3, 2]
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
The decending example you need to put the step in there or else it won't
work as above.  
Please rename all you range things except for in your strings.  I know that
those are meaningful variable names but it will cause you problems in the

Check out this tutorial.  It has all the basics in it.
lists,dicts,range,strings and other stuff.

***National City made the following annotations

This communication is a confidential and proprietary business communication.
It is intended solely for the use of the designated recipient(s).  If this
communication is received in error, please contact the sender and delete this

More information about the Tutor mailing list