Iteration in Python (Part I)

Updating Variables

A common pattern in assignment statements is an assignment statement that updates a variable – where the new value of the variable depends on the old.

x = x+1

This means “get the current value of x, add one, and then update x with the new value.”
If you try to update a variable that doesn’t exist, you get an error, because Python
evaluates the right side before it assigns a value to x:

>>> x = x+1
NameError: name 'x' is not defined

Before you can update a variable, you have to initialize it, usually with a simple assignment:

>>> x = 0
>>> x = x+1

Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.

The while Statement

Computers are often used to automate repetitive tasks.  Iteration is a common concept and  Python provides several language features to make it easier. One form of iteration in Python is the while statement. Here is a simple program that counts down from five and then says “Go!”.

n = 5
while n > 0:

    print n
    n = n-1

print ‘Go!’

Here is the flow of execution for a while statement:

  1.  Evaluate the condition, yielding True or False.
  2. If the condition is false, exit the while statement and continue execution at the next statement.
  3.  If the condition is true, execute the body and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top. Each time we execute the body of the loop, we call it an iteration. For the above loop, we would say, “It had five iterations” which means that the body of of the loop was executed five times.

Use of break Statement in loop

Sometimes you don’t know it’s time to end a loop until you get half way through the body. In that case you can write an infinite loop on purpose and then use the break statement to jump out of the loop.For example, suppose you want to take input from the user until they type done.
You could write:

while True:

    line = raw_input('> ')
    if line == 'done':
    print line

print 'Done!'

The loop condition is True, which is always true, so the loop runs repeatedly until it hits the break statement. Each time through, it prompts the user with an angle bracket. If the user types done, the break statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop. This way of writing while loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (“stop when this happens”) rather than negatively (“keep going until that happens.”).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.