[Tutor] Still Can't Find Timed While Loops
bhaaluu
bhaaluu at gmail.com
Fri Dec 7 20:54:23 CET 2007
On Dec 7, 2007 2:36 PM, Scottie Hotchkiss <shotchkiss at signalmtnlodge.com> wrote:
> Disclaimer: I can't test this while I'm at work, but using
>
> "while 1:"
>
> instead of
>
> "while time.time() - start < 30.0"
>
> would be better.
>
> In the former case if you press enter after time has run out, it won't
> print the time, in the latter you could potentially make a correct
> answer after time has run out.
>
> Example: At 29.0 you answer
> raw_input awaits and you wait 5 minutes, then answer.
> It will still run the print statement. The loop started and it doesn't
> matter how long you wait, because it won't evaluate that until the loop
> starts again.
>
> But it may alright depending on what you are trying to accomplish.
>
> Just my 2 cents,
> S Hotchkiss
>
> Tutor Lurker
>
Okay! Here's a sample 30-second Adding Game using time.time()
and a while True: loop. The timing granularity isn't all that great.
Sometimes it times out 2 or 3 seconds past 30 seconds, but in
this case, it probably isn't a big deal. This has been tested with
Python 2.4.3 running on Linux kernel 2.6.15 from the vim editor!
#!/usr/bin/python
import random
import time
startNum = random.choice(range(1, 9))
score = 0
print "#"*65
print " "*14,"Welcome to the 30-second Adding Game!"
print "#"*65
print " "* 5,"Instructions:"
print " "*10,"You'll choose a number."
print " "*10,"You'll be given a starting number."
print " "*10,"Add the number you chose to the starting number,"
print " "*10,"then keep adding your number to the sum until"
print " "*10,"the timer runs out."
print " "*10,"You'll have 30 seconds."
print " "* 5,
num2add = raw_input(" Choose a number to add: ")
print raw_input(" Press <Enter> when you're ready to begin.")
print "#"*65
num2add = int(num2add) # interpolation
newNum = startNum + num2add
print " Start with the number ", startNum
start = time.time()
while True:
if time.time() - start < 30.0:
answer = int(raw_input(" Enter your answer: "))
if answer == newNum:
print " That is correct! Keep going."
score = score + 5
newNum = newNum + num2add
print " Your score is ", score
else:
print " That is incorrect. Please try again."
print " Hurry! You only have %2.1f seconds left!"\
% (30 - (time.time() - start))
else:
break
print " Buzzz!!! Time's up!"
print time.time() - start
#print "\n"
print " Your total score was: ", score
Happy Programming!
--
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html
More information about the Tutor
mailing list