ProgFund Lect Week 5
ProgFund Lect Week 5
ProgFund Lect Week 5
(SWE –102)
Output:
The while Loop
• A while loop executes statements repeatedly
as long as a condition remains true.
• The syntax for the while loop is:
• while loop-continuation-condition:
# Loop body
Statement(s)
The while Loop: Flow chart
Figure 1
The while Loop: How it works
• Figure 1 shows the while-loop flowchart. 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.
The while Loop: Example
- count = 0
while count < 100:
print("Programming is fun!")
count = count + 1
Output:
• >>>
Programming is fun!
Programming is fun!
Programming is fun!
Programming is fun!
Programming is fun!
The while Loop: Example
- sum = 0
i=1
while i < 10:
sum = sum + i
i=i+1
• print("sum is", sum) # sum is 45
The while Loop: Example
• If i < 10 is true, the program adds i to sum.
The variable i is initially set to 1, then
incremented to 2, 3, and so on, up to 10.
When i is 10, i < 10 is false, and the loop exits.
• So sum is 1 + 2 + 3 + ... + 9 = 45.
The while Loop: Example
• Suppose the loop is mistakenly written as
follows:
- sum = 0
i=1
while i < 10:
sum = sum + i
i=i+1
The while Loop: Example
• Note that the entire loop body must be indented
inside the loop. Here the statement i = i + 1 is not
in the loop body.
• This loop is infinite, because i is always 1 and i <
10 will always be true.
• If your program takes an unusual long time to run
and does not stop, it may have an infinite loop. If
you run the program from the command window,
press CTRL+C to stop it.
Controlling a Loop with User
Confirmation
• The preceding example executes the loop five times. If
you want the user to decide whether to take another
question, you can offer a user confirmation. The
template of the program can be coded as follows:
- continueLoop = 'Y‘
While continueLoop == 'Y‘:
Execute the loop body once
# Prompt the user for confirmation
continueLoop = input("Enter Y to continue and
N to quit: ")