Chapter 5

Interation

CS1302 Introduction to Computer Programming

5.1 The while Statement

while condition:

          block

Example: print the square of all odd numbers smaller than 10.

5.2 Definite Loops vs. Indefinite Loops

Definite Loops:

we can inspect the code and determine the exact number of iterations the loop will perform.

Example: the loop will perform n times.

5.2 Definite Loops vs. Indefinite Loops

Indefinite Loops:

we cannot predict at any point during the loop’s execution how many iterations the loop will perform.

Example: the loop will end only if the user input 10.

5.3 The for Statement

range( begin,end,step )

begin = 0, step = 1 by default.

Example: print all the elements in a list.

5.4 Nested Loops

Example: given list1 and list2, create a new list whose elements are all the combinations of [m, n], where m comes from list1 and n comes from list2.

5.5 Abnormal Loop Termination

break:

the program immediately exits from the body of the loop.

Example: terminate the loop earlier when the index is 3 (before index > 4 and unsatisfy the while condition).

5.5 Abnormal Loop Termination

continue:

skips rest of the body in the loop for this iteration, and immediately checks the loop’s condition to determine whether enter next iteration.

Example: do not print when n == 2.

5.6 while/else and for/else

The code in a loop’s else block will execute when the loop exits normally, and not execute if the loop terminates due to a break statement.

 

In this example, print(count, ">=5") will execute.

5.6 while/else and for/else

In this example, print("Loop ends normally.") will not execute.

5.7 Infinite Loops

An infinite loop is a loop that executes its block of statements repeatedly until the user forces the program
to quit.

Example: while True

(the only ways to exit the loop is via a break statement, return statement, or a sys.exit call embedded somewhere within its body.

Should avoid creating infinite loops by accident.

5.7 Infinite Loops

Add conditions in while statement to control the number of iterations.

CS1302 Lecture 3 Chapter 5

By Chung Chan

CS1302 Lecture 3 Chapter 5

Lecture 3 part 2

  • 131