Iteration is the process of repeatedly executing a block of code. The ability to execute a segment of code multiple times is necessary in complex programs. It helps minimize copying and pasting code — instead of writing the same lines of code over and over again, we can simply put those lines inside a loop. Almost every programming language (including Python) offers ways to loop over a part of code.
The simplest form of iteration is the
while statement. A
while statement contains an expression header and a suite of expressions:
while <expression>: <suite>
To execute a
- execute the header expression.
- if it is
True, execute the suite of expressions and return to step 1.
This where you should be careful. The entire suite of expressions is evaluated before we return and check the header expression again. A while statement executes its suite until the header expression evaluates to a
False value. Then it stops and computer continues executing the remaining parts of the program after the while statement block. If a while statement doesn't stop it is called an infinite loop. In the Python interpreter press <Control>-C to terminate the execution.
Example: First 10 fibonacci numbers
Let's assume that one day Rohin wanted to challenge Andrew; so he asks Andrew to find a way to write out first 10 fibonacci numbers. Now fibonacci sequence is a special mathematical sequence where every other number is created by adding previous two numbers. Andrew knows that fibonacci sequence starts with 1 1 2 however lets assume that he doesn't know the rest. So he creates this logic. If he starts with first two values of fibonacci sequence he can add those two numbers to create the third number and then add the 3rd and 2nd number to create the 4th and then 4th and 3rd to create the 5th and so forth. He realizes that Rohin gave Andrew an iterative process and he can use his while statement. He writes:
i = 10 previous = 0 current = 1 while i > 0: previous, current = current, previous + current i = i - 1 print(previous)
Remember in the assignment
previous, current = current, previous + current the key thing is that before any assignment is made to previous or current first we evaluate the right part and then make the assignment. In here first thing on the right is current, and then we add previous and current and then make previous the current and finally make current the new added value. Another key thing is emphasized in the highlighted part where we decrement the value of i to make the while loop stop when it executes 10 times. Andrew gives his result to Rohin and renders him speechless.
Like in many other programming languages
for statement is used when we want to iterate over a piece of code multiple times hence it is another way to create iteration. However unlike many other languages (such as C) Python
for statement creates loop over items of a specific sequence that we provide and iterates over a piece of code inside the for statement block. Generally we use a while statement if we want to iterate a piece of code n times however with the for loop we can iterate over a sequence of items and apply our code on each item until we reach the end of the sequence. The syntax is:
for <name> in <expression>: <suite>
To execute a
for statement we fallow these steps:
- Evaluate the <expression> which must yield an iterable value (a fancy way of saying that it must return a valid sequence of items)
- For each element value in that sequence in order:
- Bind <name> to that value in the local environment.
- Execute the <suite>.
Do these steps for every value in the sequence until the end of the sequence. When we reach the end the for statement executes for the last item and stops. In retrospect for statement might be "safer" way to deal with iteration since we might not have to deal with a boolean creating an infinite loop as it is the case with the while statement. Yet while statement is still a more direct way to create iteration if we simply one to execute a piece of code n times.
Example: Iterating over a string
Lets assume that Andrew wants to get back at Rohin so he dares him to pronounce the longest english word, Pneumonoultramicroscopicsilicovolcanoconiosis, without using a vowel. Rohin thinks that if he had a list of all the characters of the word he can go over each one and write out only the consonants thus making it easier when he is pronouncing. He immediately comes up with a solution that involves a for loop. He provides the fallowing code:
vowels = ["a", "e", "i", "o", "u"] word = "pneumonoultramicroscopicsilicovolcanoconiosis" for character in list(word): if character not in vowels: print (character, end=" ") # optional 2nd argument is to print every character in one line
As you can see Rohin creates a list of all the characters of the word by
list(word), goes over each character one by one and prints out only the ones that are not vowels. To make things more interesting when we are using while or for statements to iterate, we can make nested loops by putting multiple for statements or while statements inside each other. This nested loop structure helps us iterate over a list of items inside another list of items.