Monday, May 25, 2015

Notes on Python for Informatics Chapter 5: Iteration

Source

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.
Before you can update a variable, you have to initialize it.

initialize: An assignment that gives an initial value to a variable that will be updated.
x = 0 # is equivalent to x = int()
x = 0.0 # is equivalent to x = float()
y = '' # is equivalent to x = str()
# the following are still not discussed types:
a = [] # is an empty list, and equivalent to a = list()
b = {} # is an empty dictionary, and equivalent to b = dict()
c = () # is an empty tuple, and equivalent to c = tuple()
Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement. decrement: An update that decreases the value of a variable.
increment: An update that increases the value of a variable (often by one).
x = x + 1 # is an incrementation and equivalent to x += 1
x = x - 1 # is a decrementation and equivalent to x -= 1

Loops and Iterations

Loops are used for repeating identical or similar tasks. Each time we execute the body of the loop (it has a header and a body, because it is a compound statement), we call it an iteration. We can say, “This loop had n iterations” which means that the body of the loop was executed n times.
iteration: Repeated execution of a set of statements using either a recursive function call or a loop.
iteration variable: The variable that is tested in the loop header condition for being True, every time the loop executes and therefore controls when the loop finishes.

The while statement
The while statement is used for repeated execution as long as an expression is true. 
The header of the statement has the conditional expression, which is repeatedly tested, while it yields True.

The flow of execution for a while statement:
  1. Evaluate the condition, yielding True or False.
  2. If the condition is True, execute the first suite of the body and then go back to step 1. 
  3. If the condition is False, and a second suite of the else clause is present, it is executed, and and the loop terminates.
In case of the while statement, the body of the loop should change the iteration variable, so that eventually the condition becomes false and the loop terminates.

Infinite loops 
infinite loop: A loop in which the terminating condition is never satisfied or for which there is no termination condition.
while True:
    print "This loop will never terminate" 
“Infinite loops” and break; and Finishing iterations with continue
The break statement breaks out of the smallest enclosing loop.
The continue statement continues with the next iteration of the loop.
This way, the "while True" loop can be controlled from within:

while True:
    line = raw_input('> ')
    if line[0] == '#' :
        continue
    if line == 'done':
        break
    print line

Definite loops using for 
When we have a list of things to loop through, we can construct a definite loop using a for statement. We call the while statement an indefinite loop because it simply loops until some condition becomes False whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.
Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
The break and continue statements can be used with the for loop too.
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement
A quick way to make a sequence to iterate through with the for loop is by using the built-in function range().

Loop patterns
These loops (while & for) are generally constructed by:
  • Initializing one or more variables before the loop starts.
  • Performing some computation on each item in the loop body, possibly changing the variables in the body of the loop.
  • Looking at the resulting variables when the loop completes.
Counting and summing loops
Loops are often used for counting and accumulating elements.
accumulator: A variable used in a loop to add up or accumulate a result.
counter: A variable used in a loop to count the number of times something happened. We initialize a counter to zero and then increment the counter each time we want to “count” something. 

No comments:

Post a Comment