[Tutor] Generating random in a user specified range.

Andy Joslin Andy at joslin.isa-geek.com
Tue Apr 27 13:04:01 EDT 2004

Adam wrote:

> I'm trying to develop an app where the user can specify the range in 
> which a random number will be generated from.
> [..snip..]
> The driving code is:

You need to define your functions before you call them... try moving
these four lines after the functions are defined...

> range = range()
> 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?")

Your interface is confusing... I would expect to enter the lower number
first.  Since all the data should be represented as a valid range:
(x, y) where x<y, then ask for the data in that order.

>     top = int(strtop)
>     bottom = int(strbottom)
>     range = [bottom, top]
>     print "range top is ", range[0]
>     print "range bottom is ", range[1]
>     return range
> def generatenumber(range):
>     top = int (range[0])
>     bottom = int (range[1])
>     target = random.randrange(range[1], range[0]) # and I've also tried 

Keep in mind that your top number will NEVER be selected...  you may
want to add 1 to the top number if you want it to be a valid number

> (bottom,top)
>     print "Target is ", target
>     ok = raw_input("please press enter to continue")
>     return target
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

I got the following code to work without issue...
(It is essentially your code, but compressed a bit)

import random
import string
from string import strip

def promptRange():
    return [int(strip(raw_input("What is your bottom number? "))), \
            int(strip(raw_input("What is your top number? ")))]

ref generatenumber(range):
    return random.randrange(range[0], range[1] + 1)

target = generatenumber(promptRange()) #kicks the whole thing off
print "Target is ", target

[Imagine a witty sig here]

More information about the Tutor mailing list