ITERATIONS - NTRODUCTION TO PROGRAMMING WITH PYTHON (2015)

INTRODUCTION TO PROGRAMMING WITH PYTHON (2015)

CHAPTER 7. ITERATIONS

Programs are used to automate and simplify problems. This requires repeating tasks, e.g. asking for input multiple times when a table needs to be filled. This is called an iteration of the same task. They require the interpreter to execute the same block of code multiple times.

However, this is not possible with how the interpreter normally works i.e. sequentially by moving from one block of code to the next.

This is where loop statements come into play.

They allow us to execute the same block of code as many as is needed to complete the task.

There are two main loops: theWhile Loopand theFor Loop.

Both loops rely on updating variables. So far we have only created and used variables, without changing and updating the original value of the variable during execution. Here’s an example of updating variables:

a = 1

b = a+2

b = 2*b

a = b-a

print (a, b)

The program is executed step-by-step, top to bottom. Here’s how the variables get updated at each line:

Line

Value of ‘a’

Value of ‘b’

Details

1

1

-

2

1

3

a =1, so a+2 = 1+2 =3

3

1

6

b = 2*b. Now b=3, so 2*b= 2x3=6

4

5

6

b-a = 6-1 =5

5

5

6

print: 5 6

The interpreter always executes the commands in a sequential order, updating any variables that are changed during the process.

The loop statements break this sequential flow, allowing us to access functions defined anywhere in the whole code.

Loop Control Statements

When should the loop start? How long should it continue, and when should it terminate?

This is achieved using loop control statements.

Without them, the interpreter will either not execute the loop or if it does will never get out of it. Let’s see how it works practically.

List Types and Range Functions

To use the for-loop, it is important to understand list type. Lists are ordered sequence of data. Some examples include:

[‘white’, ‘red’, ‘green’]

[1, 2, 3, 4, 5, 6]

[‘word’, 34, ‘another word’, -4, ‘last’]

[] # completely empty list

The basic for-loop relies on the list type.

THE FOR-LOOP

This loop iterates (repeats) a function or set of commands for the fixed number of parameters you give it. This is different from the While-Loop, which runs as long as a condition is true.

For example:

· If it is raining outside, take the rain coat.

· While the sun shines, the monks continue working tirelessly on the field

Hence, unlike the while-loop, the for-loop runs once.

The syntax of the for loop is

for variable/function in sequence/list:

indented statements to loop

Here’s an example:

for count in [1, 2, 3]:

print(count)

print('Go' * count)

The above for-loop has the for-statement, the variable which it has to work on, and the list of parameters it has to work with.

The loop has three parameters and a variable. When it is executed, the two lines of code are repeated three times, once for each list parameter.

Line

Value in ‘count’

Details

1

1

Takes first element from list

2

1

print 1

3

1

Apply operator ‘Go * 1 equal ‘Go’; prints Go

1

2

Update value to next element

2

2

print 2

3

2

‘Go * 2 equals ‘GoGo’; prints Go Go;

1

3

change count to the next element in the list

2

3

print 3

3

3

‘Go’ * 3 is ‘GoGoGo’; prints GoGoGo;

List complete, done.

In this case, the for-loop performs two actions: updating the variable in place of ‘item’, and running the indented block of code after. The above example used the variable within the loop as well.

A simpler loop can also be created without using a list. This is where Range (a pre-made function in Python) can be used.

for x in range(7):

print('For-Loop')

Notice that the variable x is not used inside the body of the for-loop. You can choose the number of times the loop must iterate or repeat itself.

# a program for specified repetitions

n = int(input('How many times do you want to repeat this?: '))

for x in range(n):

print('Repeating…')

On execution, the program will print the statement ‘Repeating…’ n number of times i.e. the number you enter in the beginning.

THE WHILE LOOP

It is a Boolean loop that repeats the same set of command until the original condition is False.

The syntax for the while loop in Python programming language is:

while expression:

indented statement(s)

As long as the expression (its Boolean condition) holds true, the indented block of code will be executed again and again. The moment the condition becomes false, the program moves out the loop and executes the next line outside of it.

Example

n = 0

while (n< 5):

print ('I have counted till: ', n)

n = n+ 1

print ("Good bye!")

The above while-loop holds true for as long as the updated ‘n’ has a value less than 5. The moment it reaches 5 the program will move to the first line outside of the loop (the un-indented line).

Good bye!

How about a loop that can never end?

An infinite loop where the false condition does not exist? These loops are important for keeping the program running and seeking continuous input from the user. If an infinite loop was not running, any smart device or PC would shut down after loading (completing loading) its operating system.

A loop becomes infinite loop if a condition never becomes FALSE.

n = 1

while n == 1 : # This is the official secret for constructing an infinite loop

a = input("Enter a value:")

print ("You entered: ", a)

print "Good bye!"