Professional Documents
Culture Documents
ICT Lecture 23-24-25 (Loops)
ICT Lecture 23-24-25 (Loops)
Computing
Outline
While Loop
Conditionals within a Loop
Counting using while Loop
break & continue Statements
For Loop
Conditionals within a Loop
Counting Using for Loop
in Operator with for Loop
Nested Loops
Nesting while Loop
Nesting for Loop
Nesting while inside for Loop
Nesting for Inside while Loop
A loop can be used to tell a
Introduction program to execute
statements repeatedly.
while loop-continuation-condition:
# Loop body
Statement(s)
4
The while Loop
A single execution of a loop body is called an
iteration (or repetition) of the loop.
Each loop contains a loop-continuation-condition,
a Boolean expression that controls the body’s
execution.
It is evaluated each time to determine if the loop body
should be executed.
If its evaluation is True, the loop body is executed;
▪ otherwise, the entire loop terminates and the program
control turns to the statement that follows the while loop.
5
6
7
Controlling a Loop with User
Confirmation
8
Controlling a Loop with a Sentinel
Value
9
The Break and Continue Statements
Often you know exactly how many times the loop body
needs to be executed, so a control variable can be used to
count the executions.
A loop of this type is called a counter-controlled loop.
The syntax of a for loop is:
for var in sequence:
# Loop body
A sequence holds multiple items of data, stored one after the other.
The variable var takes on each successive value in the sequence.
12
The for Loop
Often you know exactly how many times the loop body needs to be executed,
so a control variable can be used to count the executions. A loop of this
type is called a counter-controlled loop.
13
The for Loop
The function range(a, b) returns the sequence of integers a, a + 1, ..., b -
2, and b - 1.
For example,
16
Nesting While Loops
21
Summary
While Loop
Conditionals within a Loop
Counting using while Loop
break & continue Statements
For Loop
Conditionals within a Loop
Counting Using for Loop
in Operator with for Loop
Nested Loops
Nesting while Loop
Nesting for Loop
Nesting while inside for Loop
Nesting for Inside while Loop