We will now study iteration as explained in Chapter 6 of the book. In Wikipedia, iteration is defined as repeating a process with the aim of approaching a desired goal.
Python provides a number of constructs for iterations (i.e. repetitions) and one of the most useful is the while statement. The statement is used in the following fashion:
while condition: statement1 statement2 statement3 statement4
statements 1, 2 and 3 will be repeated while the condition is True. As soon as the condition becomes False, the while loop stops and statement 4 executes. In other words, this is a possible flow of execution:
statement1 statement2 statement3 statement1 statement2 statement3 statement1 statement2 statement3 statement4
Work out the exercises in section 6.3 (countdown, sequence and num_digits). Comment on the condition used for the while loop in the num_digits function. Is there something better we can use?
Looping constructs can be used to generate tabular data like a multiplication table. Work out the programs in section 6 until part 6.12. The last program can be nicely used to print out any multiplication table e.g.
Programs generally solve a problem. And the steps needed to solve a problem in a satisfactory manner is called an algorithm. Section 6.14 shows an algorithm, Newton’s method for calculating the square root of a number. Run it and make sure you understand how it works. Where does the name algorithm come from?
Work out the exercises 1-9 at the end of Chapter 06. Some of the exercises are relatively challenging but we would advise you to work hard trying to find the solutions. Do not hesitate to contact us if you are stuck.