Saturday, November 12, 2011

Iteration

To iterate means to "do again." In programming, iteration performs a series of actions, over and over, until a specific condition is met.

There are two main types of iterative statements in Python.

  • while loops
  • for loops

In this example, we set a variable "i" to the value 5.

We then start the while loop. The statement reads, while the value of "i" is greater than zero (0), perform the following statements. The statements to be performed are indented under the while loop. There are two things to do. First, print the value of "i". Secondly, set "i" to the value of "i" less one (1). The second statement will reduce the value of "i" successively until it reaches zero. Until that happens Python will start the loop again.

So the first time around, "i" is 5. So the loop prints "5". Then "i" becomes "4". This is still greater than zero so the loop prints "4". Then "i" becomes "3". And so on.

Here's another example.


In this example, we set a variable "i" to 5. Once again, we're going to iterate two statements, until "i" becomes zero or less. The statement "while i > 0" instructs the loop to continue iterating till that condition is met. The two statements to be carried out are; assign the variable "c" to the value "c + 'a'". Essentially this means, concatenate the letter "a" to the existing value of "c" and then assign that to a variable "c". It's not the same one as we'll see later. But Python takes the existing value of "c" which is blank initially, does the concatenation, and then assigns it to a variable "c". Once that's done, it reduces the value of "i" by one.

Once the loop is completed, we print out the value of "c". As you can see, it has five "a"'s. 

If you forget to include the statement "i = i - 1", then the value of "i" never gets reduced. You'll run into what is called an "infinite loop." This is when the loop continues on forever. Infinite loops are an example of a common programming error with both novice and experienced programmers.

The other type of loop is a for loop. For loops are particularly interesting in Python because they operate on a list of items. The list has to be predefined. For example, the following is a list of numbers that the for loop will print. We haven't discussed the list object in Python yet, this list is a special type of list in Python called a Tuple and it's enclosed in parentheses.


Quite simply, what this does is assign each element of the list to the variable "i" at each iteration of the loop.

Here's another one, using a string. Yes, Python iterates strings!


The print statement in Python adds a carriage return to each output. This is normally OK. However, if you don't want each letter to print on it's own line, add a comma at the end of the print statement.


That's it for loops for now.

No comments:

Post a Comment