[Tutor] command error

Steven D'Aprano steve at pearwood.info
Tue Feb 16 23:53:19 CET 2010


On Wed, 17 Feb 2010 07:32:44 am Shurui Liu (Aaron Liu) wrote:
> Here is a program I wrote, I don't know why I cannot exit when I
> tried 10 times? Hope somebody can help me. Thank you!

Here is a program that loops ten times, then stops:


for i in range(10):
    print "Loop number", i


Here is another program that loops ten times counting down backwards:


for i in range(10, 0, -1):  # 10, 9, 8, ... , 1
    print "Loop number", i


Lastly, here is a program that loops ten times backwards, but exits 
early when a test becomes true. As a bonus, it prints a message if the 
test never becomes true:


for i in range(10, 0, -1):  # 10, 9, 8, ... , 1
    if i <= 4:  # the test
        print "we exit the loop early"
        break
    print "Loop number", i
else:  # for...else
    print "we didn't exit the loop early"



-- 
Steven D'Aprano


More information about the Tutor mailing list