Fundamentals » Repetition Statements »


Repetition Statements

Selection Statements Table Of Contents Defining Functions

Python provides two looping constructs — the while loop and the for statement — both of which work and serve the same purpose as they do in Java.

The While Loop

The while loop is the most general looping construct. It can be used for constructing both event-controlled and count-controlled loops. Consider the following code segment which sums the first 100 integers

theSum = 0
i = 1
while i <= 100:
   theSum = theSum + i
   i = i + 1

print "The sum = ", theSum

which would be equivalent to the following in Java

int theSum = 0;
int i = 0;
while( i <= 100 ) {
  theSum = theSum + i;
  i = i + 1;
System.out.println( "The sum = " + theSum );

The while loop is a compound statement and thus requires a statement block even if there is only a single statement to be executed. Consider the user of the while loop for user input validation

value = 0
while value < 0 :
   value = int( raw_input( "Enter a postive integer: " ) )

Python, like Java, provides the break and continue jump statements for use in loops. As a review, the break statement is used to break out of or terminate the inner most loop in which t is used. The continue statement immediately jumps back to the top of the loop and starts the next iteration by evaluating the condition.

For Loops

The for loop in Python is more than a simple construct for creating general count-controlled loops as in Java. Instead, it is a generic sequence iterator that can step through the items of any ordered sequence object. The general syntax of the for loop is as follows

for <loop-var> in <object> :

The body of the loop (statement-block) is executed once for each item in the ordered sequence. Before beginning each iteration, the current item of the ordered sequence is assigned to the loop variable (loop-var).

Single Step Iterations

The Python for loop will be very handy for sequence iterations with lists, tuples, strings and other objects. For now, however, we are going to focus on its use for creating simple count-controlled loops like those found in Java. Consider the following Java code segment

// Java count-controlled loop.
for( int i = 1; i <= 10; i++ )
  System.out.println( i );

which prints the range of integers from 1 to 10, one per line. The equivalent in Python would look as follows

for i in xrange( 1, 11 ) :
   print i

The xrange() function creates an iterator object which iterates over the integers, one at a time, from 1 through 10 inclusive. Python also has the range() function which can be used instead. The range() function generates the ordered sequence of integers [1..11) that will be assigned to the loop variable, one at a time. The starting value is always a part of the sequence, but the end value is never part of the sequence. The xrange() function is more efficient since a physical list is not created.

Variable Step Increments

Instead of stepping or counting by 1, a third argument can be provided to the xrange() function to indicate the step value.

for i in xrange( 0, 51, 5 ) :
   print i

Here, the loop prints the multiples of 5 between 0 and 50 including both 0 and 50. To construct a loop which decrements through the indices as illustrated in the following Java loop

// Java loop
for( int i = 10; i > 0; i-- )
  System.out.println( i );

use arguments for the range() function similar to those shown below

for i in xrange( 10, 0, -1 ) :
  print i

Iterating From Zero

Incrementing loops which start with an index of 0 are very common. Therefore, the xrange() function has a special version which starts at 0 and iterates a specified number of times. In the following example,

for i in xrange( 20 )
   print i

the loop prints the integer values from 0 through 19 one per line. Here, the argument to the xrange() function indicates the number of iterations, starting from 0.

Example Program

The following program illustrates the user of a loop to extract data from the user and compute an average value.

# Reads a group of positive integer values from the user,
# one at a time, until a negative value is entered. The average
# value is then computed and displayed.

# Initlize the counting variables.
total = 0
count = 0

# Extract the values.
value = int( raw_input( "Enter an integer value (< 0 to quit): " ) )
while value >= 0 :
   total = total + value
   count = count + 1
   value = int( raw_input( "Enter an integer value (< 0 to quit): " ) )
# Compute the average.
avg = float( total ) / count

# Print the results.
print "The average of the", count, "values you entered is", avg

Processing Strings

The for loop is also handy for processing each character within a string. Consider the following sample program which iterates through the contents of a string and counts the number of vowels.

# This program iterates through a string and counts the number of
# vowels it contains.

# Extract a string from the user.
text = raw_input( "Enter a string to be evaluated: " )

# Iterate through the string.
numVowels = 0
for ch in text :
   if ch in "aeiou" :
      numVowels = numVowels + 1
# Print the results.
print "There are " + str( numVowels ) + " vowels in the string."

You will notice that the keyword in is used with both the loop and the selection statements in this example. In the for loop, in is simply a word required as part of the construct. But when used with the selection statement, it is a logical operator which determines if a substring is within the given string.

Selection Statements Table Of Contents Defining Functions

© 2006 - 2008: Rance Necaise - Page last modified on July 31, 2008, at 11:16 AM