Week 5 (Repetition Structures)
Week 5 (Repetition Structures)
Week 5 (Repetition Structures)
Learning Objectives
• Define why we need Loop Statements.
OR
• Loops can execute a block of
code number of times until a
certain condition is met. Iteration
Loops
In Loops, the program knows beforehand about
how many times a specific instruction or set of
instructions will be executed.
Initial Loop Update
Keyword Statement Condition statement
}
Loops in Python
In Loops, the program knows beforehand about how
many times a specific instruction or set of
instructions will be executed. This is called Counter
Loop Loop Initial Update
Keyword Condition Statement statement
Initial
Statement
False
End
Other Types of Loops
Now, What if we don’t know beforehand how many
times a set of instructions will be executed?
Conditional Loops
In Such cases, we will use Conditional Loops. I.e., we
will execute the loop until a certain condition is met.
while (condition):
{
//body Body of Loop
}
While Loop in Python
Then we will use Conditional Loops. I.e., we will
execute the loop until a certain condition is met.
while condition :
//body Body of Loop
Conditional Loop: Working Example
Suppose, the requirement is to keep taking numbers
as input from the user until the user enters -1.
Conditional Loop: Working Example
Suppose, the requirement is to keep taking numbers as
input from the user until the user enters -1.
Enter -1 to exit.
Enter a number: -1
Conditional Loop: Working Example
Loop Body of
Condition while loop
true
False
Code Repetition: Problem
Is there any way, we can stop the loop before it has
looped through all the items?
Code Repetition: Solution (Break)
for x in range(1,100,1):
if x == 5 :
break
print(x)
//Remaining code
Output
1 2 3 4
Code Repetition: Problem
Is there any way, we can stop the current iteration
of the loop, and continue with the next?
Code Repetition: Solution (Continue)
for x in
for x in range(1,100,1):
if x == 5:
continue
print(x)
//Remaining code
Output
1 2 3 4 6 7 8…
Working Example