February 19th, 2006, 03:18 PM

Countdown
how can i count down from a number like 10 and then when it reaches 1 it will exit or something.
I have tried this:
>>> import sys
>>> for i in range(1,10):
if i < 2:
sys.exit()
February 19th, 2006, 03:40 PM

Code:
import sys
for i in range(10)[::1]:
print i
if not i: sys.exit()
[::1] reverses the list returned by range().
The loop iterates 0 to 9, that is 10 numbers it goes through. When it equals 0, it exits. Remember that FALSE equals 0, while TRUE equals 1. So 'if not i' is the same as 'if i is 0'/'if i == 0'.
Comments on this post
Last edited by †Yegg†; February 19th, 2006 at 03:43 PM.
February 19th, 2006, 04:24 PM

February 19th, 2006, 04:28 PM

so what if i wanted it to count down by seconds. And it would exit after soo many seconds.
February 19th, 2006, 04:34 PM

Code:
import sys, time
for i in range(10)[::1]:
print i
if not i: sys.exit()
time.sleep(1)
This exits when it hits 0, which is 10 seconds.
February 19th, 2006, 04:46 PM

nice thats what i was looking for. thank you. I was trying something like that but i couldnt figure it out.
Comments on this post
February 19th, 2006, 04:58 PM

Why don't you just count down?
Code:
>>> help(range)
Help on builtin function range in module __builtin__:
range(...)
range([start,] stop[, step]) > list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
>>>
>>> range(10, 1, 1)
[10, 9, 8, 7, 6, 5, 4, 3, 2]
>>>
>>> range(9,0,1)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
Or if you do want something reversed, a more readable answer than [::1] is:
Code:
>>> for i in reversed(range(10)):
>>> ...
>>>
Comments on this post
February 20th, 2006, 05:38 PM

I didnt think of that thanks! that does look easier.