Previous | Next


Usually, a loop simply executes a block until its condition becomes false, or until it has used up all sequence elements. But sometimes you may want to interrupt the loop, to start a new iteration (one “round” of executing the block), or to simply end the loop.

break

With break, it allow you to end a loop. Let’s try the following sample code:

x = 0
while x < 100:
  if x > 10:
    print 'i am tired!'
    break

  print x
  x += 1

The result:

0
1
2
3
4
5
6
7
8
9
10
i am tired!

The while loop check the value condition of x so that it stop to loop if x is greater than 100. In the while-processing statements, there is a if expression to check if x is greater than 10 or not, if it return true, it then print a statement (‘I am tired!’) and terminate the loop. Otherwise, it continue to execute the inner block of statements where it will print the value of x and increase the value of x by 1 every time it execute the block of statement.

continue

With continue, it won’t terminate the loop. It causes the current iteration to end, and to continue with the next iteration. It basically means “skip this and continue with the next element in the loop”. Let’s try the following sample code with a simple list:

numbers = [0,1,2,3,4,5,6,7,8,9]
for x in numbers:
  if x == 5:
    print 'kick the 5 out'
    continue

  print x

The result:

0
1
2
3
4
kick the 5 out
6
7
8
9

The for loop start to print the value of each element in numbers. In the for-loop processing code, there is a if expression to check if current element is equal to 5 or not, it print a statement (‘kick the 5 out’) if the expression return true. Notice that, it never terminate the for loop. It continue to print until it reach its last element.

 


Previous | Next