[Tutor] Generating random in a user specified range.

denis denis.spir at free.fr
Tue Apr 27 13:03:59 EDT 2004


----- Original Message -----
From: David Broadwell <dbroadwell at mindspring.com>
To: <tutor at python.org>
Sent: Tuesday, April 27, 2004 6:17 PM
Subject: RE: [Tutor] Generating random in a user specified range.


<snip>

> 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

<snip>

> 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?

Well, It seems you confuse things, Adam, in fact notation and content of a
variable. Python has a built-in function called range() which generates a
full sequence of integers :

>>> range(5,8)
[5, 6, 7]

Now if we iterate on it, we'll loop for 5 and 6 and 7 :

>>> for n in range (5,8) :
        print '*%i*' %n
*5*
*6*
*7*

Let's do the same with a 'custom' range like yours, that I will temporarily
call R :
R = [5,8]
>>> for i in R :
        print '*%i*' %i
*5*
*8*

R is a raw list of two values, holding what we interpret as range border.
That's good reason to call it e.g. RangeBorders.


> > top = int(strtop)
> > bottom = int(strbottom)
> > range = [bottom, top]            # indexes are : 0 <-> bottom , 1 <->
top
> > print "range top is ", range[0]
> > print "range bottom is ", range[1]

Here, your print statements swap bottom (first --> index 0) and top
(second --> index 1). You do the same mistake in the generatenumber function
:

> > def generatenumber(range):
> >      top = int (range[0])
> >      bottom = int (range[1])
> >      target = random.randrange(range[1], range[0])

It shouldn't work, it doesn't.
(As Alan writes : 'hope it help')

denis




More information about the Tutor mailing list