Looping is a very useful technique that performs repetitive tasks until user-specified condition(s) are fulfilled. There are two kinds of loops in Python, the while loop and the for loop.

The while loop

This type of loop keeps executing a block of code as long as some specified condition holds true. The basic syntax of the while loop is:

while Boolean_expression: # True => execute the following code block
    statement1
    statement2

For example, by introducing a counter it is possible to make a while loop repeat some integer number of times:

Take care to avoid creating infinite loops which never complete and won't be exited (e.g., by forgetting to increment the count variable in the code snippet above).

The break and continue statements

Occasionally, we need to put extra exit points in the body of a loop in order to avoid the undesired execution of some part of the code. The break and continue statements allow us to do this. The break statement causes an immediate jump out of the loop. The continue statement stops the current iteration of the loop and proceeds the next iteration, jumping to the top of the loop. Obviously these statements will generally appear within an if-else construct; it would not be very useful to include unconditional jumps within a loop.

The following example illustrates the difference between break and continue:

In the first loop, break provides an exit point when count reaches 3. Thus, the code prints “We’re outta here!” instead of “3” and leaves the loop at break. The last iteration never occurs, and “4” does not appear in the output. In the second loop, however, the continue statement just cuts short the iteration when count reaches 3, and the loop advances to the next iteration. Thus, “See you next time!” is printed instead of “3”, but the loop then continues normally to the final iteration and prints “4”.

Mini-exercise: while-loop for user input

A while-loop works well in codes like our earlier one for reading user input. The while-loop will just keep reading numbers until the user gets it right (maybe never!). If you like, you can use the solution to the previous mini-exercise as your starting point.

  • Prompt the user to enter an integer
  • As long as the input number is not an integer, continue to ask the user to enter an integer [Hint: Use the same test as in the if/else exercise]
  • After an integer is received, print the message, "The integer that you entered was: " along with the integer
 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement