[Tutor] While Loops and Modules

bhaaluu bhaaluu at gmail.com
Thu Dec 6 14:19:42 CET 2007


Greetings,

On Dec 6, 2007 12:44 AM, earlylight publishing
<earlylightpublishing at yahoo.com> wrote:
> Hello again to all the wonderfully helpful folks on this list.  Today I did
> my Google homework and I found this neat bit of code for a countdown timer.
>
> import time
> import threading
> class Timer(threading.Thread):
>     def __init__(self, seconds):
>         self.runTime = seconds
>         threading.Thread.__init__(self)
>     def run(self):
>         time.sleep(self.runTime)
>         print "Buzzz!!! Time's up!"
> t = Timer(30)
> t.start()
>
> I don't understand large chunks of it (don't know what threading, self, or
> __init__ mean) but that's not important at the moment.  It works and I will
> learn the vocab eventually.

That is a good start! Get it working first, then figure it out later. 8^D

>
> I also wrote this bit of code for a math challenge which comes in the next
> part of my game.
>
> import random
> startNum = random.choice(range(1, 9))
> newNum = startNum + 7
> score = 0
> print 'Start with the number ', startNum, '.  Then continuously add 7 to
> that number until the timer runs out.  You have 30 seconds.'
>
> answer = int(raw_input('Enter your answer: '))
> if newNum == answer:
>     print 'That is correct!  Keep going.'
>     score = score + 5
>     print 'Your score is ', score
> else:
>     print 'That is incorrect.  Please try again.'
>
> I understand this part just fine 'cause I actually wrote it myself.
>

A couple of things which may help you when you're testing/debugging
your programs:

type(object)
dir(object)

Play with those in the interactive interpreter to see what they do, for example:
>>> a = 7
>>> type(a)
<<type 'int'>
>>> a = "time"
>>> type(a)
<type 'str'>
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random',
'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill',
'_BuiltinMethodType', '_MethodType', '__all__', '__builtins__',
'__doc__', '__file__', '__name__', '_acos', '_cos', '_e', '_exp',
'_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt',
'_test', '_test_generator', '_urandom', '_warn', 'betavariate',
'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits',
'getstate', 'jumpahead', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed',
'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']

etc.

Another little trick I use to watch the values of variables and set breakpoints:

print variable_Name
raw_input("Pause")

I just insert those two lines after each variable I want to watch (perhaps
to see if it is actually doing what I think it is supposed to be doing?).


> What I need to do now is put these two parts together so that the player
> will keep adding 7 to the starting number for 30 seconds then the loop
> breaks.  I know I need a loop of some sort and I'm guessing it's a 'while'
> sort of thing.  I couldn't find what I was looking for when I Googled.  I'm
> not even sure I knew the right search terms.  Does anyone know how I'd
> combine these two modules to make it work?
>

while True: or while 1: do the same thing, and they are a generic infinite loop.
You can use the keyword break somewhere inside the loop to break out of it.

When you figure out what condition  must be met to quit the while loop,
you can replace the True or 1 with your condition.

For example, working with the snippet you supplied:
import random
import time
import threading

class Timer(threading.Thread):
    def __init__(self, seconds):
        self.runTime = seconds
        threading.Thread.__init__(self)
    def run(self):
        time.sleep(self.runTime)
        print "Buzzz!!! Time's up!"
t = Timer(30)
startNum = random.choice(range(1, 9))
newNum = startNum + 7
score = 0
t.start()
print 'Start with the number ', startNum, '. Then continuously add 7
to that number until the timer runs out.  You have 30 seconds.'
while 1:
    answer = int(raw_input('Enter your answer: '))
    if newNum == answer:
        print 'That is correct!  Keep going.'
        score = score + 5
        print 'Your score is ', score
        newNum += 7
    else:
        print 'That is incorrect.  Please try again.'

That isn't quite working as it should, but I only added a couple of lines
and did the requisite indentation for the while loop. It might be enough
to keep you going for a wee bit?

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m


More information about the Tutor mailing list