while loops

The while loop is a standard workhorse of many languages. Essentially, the program will continue doing something while a certain condition exists. As soon as that condition is no longer true, the loop stops.

break and continue work exactly the same as in C. The equivalent of C's empty statement (a semicolon) is the pass statement, and Python includes an else statement for use with breaks.

The break statements simply force the loop to quit early; when used with nested loops, it only exits the innermost enclosing loop. The continue statements cause the loop to start over with the next iteration, regardless of any other statements further on in the loop. The else statement block is run "on the way out" of the loop, unless a break statement causes the loop to quit early.

The following example demonstrates a generic while loop:

1 while <test>: 
2     <statements> 
3      if <test>: 
4          break 
5      elif <test>: 
6          continue 
7      else: 
8          <statements> 

Line 1 declares the condition that is tested. As long as this condition is true, the loop will continue. Once it is no longer true, the loop quits.

Line 2 indicates the main logic of the loop that is performed during each iteration.

Line 3 tests a particular condition, usually whether the initial condition is still true. If line 3 is a true statement, the loop quits. If not, the control moves to line 5, which is yet another test. In this case, if the test condition is true, the loop immediately starts again and ignores the following logic.

Line 8 is executed when the looping condition is no longer true.

Following screenshot shows a simple while loop that loops 10 times before the test condition causes it to stop. When the loop is finished, the else statement ensures a final operation is performed, in this case printing a string:

Simple while loop

Following screenshot shows a more complex loop. In this case, it counts down from 50, printing all even numbers. Once the number 10 is reached, the loop quits. The % symbol is the modulus operator and is explained later in this book:

More complex while loop
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.209.131