Loops – Python

Overview

By the time students see loop constructs, they have an understanding of the use of variables and the flow of execution of code.  The loop constructs in Python are while and for-loops (they correspond to repeat until and repeat in Scratch).  Some insights:

  • There appears to be no consensus on whether a while or a for-loop is easier to understand and which should be taught first. Textbooks vary on which loop is introduced first; what is easier can be language dependent and is often left to the instructor.
  • Loops are a great opportunity to clarify remaining misconceptions about the use of variables and the flow of execution.
  • Difficulties with tracing and writing loops are often tied to misconceptions and earlier topics not yet fully mastered.
  • One indication that students have mastered the use of variables, flow of execution, and use of loops is their ability to take a loop consisting of many iterations and determine the outcome of the loop without having to trace it.  This type of comprehension is tested on the AP Java exam.

This document discusses twelve loop examples in Python. The examples are:

For Loops in Python

1. Why do we need loops? (with video)
2. Finding the characters appearing in both strings
3. Printing multiples of 6 and 10
4. Who gets the better deal? (with video)
5. Palindromes

While Loops in Python

6. Summing the digits in an integer using a while loop
7. Guessing a letter in the alphabet
8. Using of a sentinel value in a while loop

While vs. For Loops

9. Converting a for-loop into a while loop
10. Are these loops doing the same thing?
11. Summing the digits in an integer using a for–loop (with video)
12. Finding the greatest common divisor of two integers

With the exception of short demonstration code, the Python programs we use are available for downloading. The names of the Python files are listed in each code.  While every attempt was made to have the code listed in a blog be the same as the code in the program, we expect that there can be minor differences. In such a case, the Python program is the later version. Four video clips on loops are currently available; two for problems in this document and two related to nested loops.

All the programs are written using Python 2.7x.  Python 2.7x has two ways to input integers, input() and int(raw_input()). In our programs, we use int(raw_input()) as our default method to input integers. Running the programs in Python 3.x will produce an error as raw_input() is no longer available in Python 3.x. Input statements would need to be changed.