[Tutor] Generating random in a user specified range.

David Broadwell dbroadwell at mindspring.com
Tue Apr 27 12:17:56 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 integer, but it still
> complains.
Can you post in those tracebacks?

> Any advice on what I can do to fix this?
well, let's look over the program;

> range = range()
>>> range = range()
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in ?
    range = range()
TypeError: range() requires 1-3 int arguments

I think you should be asking for a list here.
try:
range = [] instead.

> print range
> raw_input("click ok to carry ok")
> target = generatenumber(range) #kicks the whole thing off
>
> 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

line by line ...

> 	strtop = raw_input("What is your top number?")
> 	strbottom = raw_input("What is your bottom number?")

What you have above, is very readable, but can also be expressed as without
really sacraficing readability;

 	top = int(raw_input("What is your top number?"))
 	bottom = int(raw_input("What is your bottom number?"))
 	range = [bottom, top]

You are trying to use your 'range = range()' as if it were a list range =
[bottom, top] ... if you WANT a list, then ask for with a 'range = []'
statement as shown above.

 	print "range top is ", range[0]
 	print "range bottom is ", range[1]
 	return range

and you are using range like a range ... so as a recomndation your variable
being named 'range' is bad namespace ettiquitte. how about rangelist = []
instead?

> 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)
       # and probably gotten bad results too, range isn;t really a list
>      print "Target is ", target
>      ok = raw_input("please press enter to continue")
>      return target

--

Programmer's mantra; Observe, Brainstorm, Prototype, Repeat

David Broadwell




More information about the Tutor mailing list