[Tutor] guess]

Alan Gauld alan.gauld at btinternet.com
Wed Oct 4 21:23:09 CEST 2006


> def number(number):
>     ran=input("range  >")
>     ran=ran+1
>     from random import randrange
>     guessed=[]
>     guess=randrange(ran)
>     print guess
>     guessed.append(guess)
>     guesses=1
>     guessed=[]      <---- Why do you reset guessed to an empty list 
> here?

also couldn't the whole chunk above be moved into the loop?
see below

>     while guess !=number:
>         guess=randrange(ran)
>         if guess not in guessed:
>             guessed.append(guess)
>             guesses=guesses+1
>             print guess
>
>     print"i got the number",number,"in",guesses,"guesses"

# keep imports outside functions.
from random import randrange

def number(number):
     ran=input("range  >") + 1
     guessed=[]
     guesses = 0   # need to initialise it first
     guess=randrange(ran)
     while guess != number:
         if guess not in guessed:
             guessed.append(guess)
             guesses += 1
             print guess
         guess=randrange(ran)
     print "i got the number",number,"in",guesses,"guesses"

You might also want to add a check to see if ran < number

Also I'm not sure why you don;t count duplicate guesses?
But that's your choice I suppose. However if you counted them
you can remove the list entirely...

Does that help?

-- 
Alan Gauld
Back from vacation... 




More information about the Tutor mailing list