week5
week5
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 Conditio Stateme statemen
n nt t
Initial
Statement
Loop
Body of Update
Conditio
for Loop Statement
n True
Fals
e
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.
Keywo Loop
rd Condition
while
(condition)
{ Body of
Loop
//body
}
While Loop in Python
Then we will use Conditional Loops. I.e., we
will execute the loop until a certain condition
is met.
Keywo Loop
rd Condition
while
condition : Body of
Loop
//body
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.
# This program adds 100 odd numbers
num = 0
while (num != -1):
print(‘Enter -1 to exit.’)
num = int(input(‘Enter a number: ’))
Enter -1 to exit.
Enter a number: -1
Conditional Loop: Working
Example
Loop
Body of
Conditio
while loop
n true
Fals
e
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):
print(x)
if x == 5 :
break
//Remaining code
1234 Outpu
t
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):
print(x)
if x == 5:
continue
//Remaining code
1 2 3 4 6 7 8… Output
Working Example