Chapter Overview
Learning Objectives
By the end of this session, students should be able to:
- Explain the purpose of the
whileloop. - Understand how a
whileloop executes repeatedly. - Write simple Python programs using a
whileloop. - Explain what an infinite loop is.
- Identify the common cause of an unintended infinite loop.
- Explain the use of
elsewith Python loops. - Differentiate between normal loop completion and termination using
break.
1. Quick Recap: What is a Loop?
A loop is a programming construct that allows a set of statements to be executed repeatedly.
Loops are useful when a task has to be performed multiple times.
Python provides several ways to create loops, including the
for loop and the while loop.
If we want to print the numbers from 1 to 5, we could write
repeated print() statements. A loop allows us
to perform the same task more efficiently.
2. The while Loop
The while loop repeatedly
executes a block of statements as long as its condition
remains True.
Basic Syntax
while condition:
statement(s)
The condition is checked before every iteration of the loop.
If the condition is True, the loop body executes.
When the condition becomes False, the loop stops.
3. How Does a while Loop Work?
If the condition becomes False, execution moves to
the statement following the loop.
4. Example: Printing Numbers Using while
count = 1
while count <= 5:
print(count)
count = count + 1
Output
1
2
3
4
5
How It Works
-
countstarts with the value1. -
Python checks whether
count <= 5. - If the condition is true, the value is printed.
-
countis increased by 1. - The condition is checked again.
-
The loop stops when
countbecomes 6 because6 <= 5is false.
5. Why Must We Update the Loop Variable?
In many while loops, the condition depends on a
variable whose value changes during each iteration.
count = 1
while count <= 5:
print(count)
count = count + 1
The statement
count = count + 1
changes the value of count. Eventually the condition
becomes false and the loop terminates.
while loop, always make sure that
there is a clear path toward making its condition false, unless
an infinite loop is intentionally required.
6. Example: while Loop with User Input
A while loop can be useful when the number of
repetitions depends on user input.
number = 1
while number <= 3:
name = input("Enter a name: ")
print("Hello", name)
number = number + 1
The loop asks for a name three times because the variable
number is increased after each iteration.
7. What is an Infinite Loop?
An infinite loop is a loop that continues
executing because its condition never becomes
False.
Example
count = 1
while count <= 5:
print(count)
This loop keeps printing 1 because the value of
count is never changed.
count remains 1, the condition
count <= 5 remains true forever.
8. Intentional Infinite Loops
Infinite loops are not always programming mistakes. Sometimes a program is intentionally designed to keep running until a particular event occurs.
while True:
command = input("Enter command: ")
if command == "quit":
break
print("You entered:", command)
Here, while True creates a loop whose condition is
always true. The break statement provides a way to
leave the loop when the user enters "quit".
- Interactive command programs.
- Game loops.
- Systems that continuously monitor events.
- Programs that wait for incoming tasks.
9. The break Statement
The break statement immediately terminates the
nearest enclosing loop and transfers control to the statement
following that loop.
while True:
number = int(input("Enter a number: "))
if number == 0:
break
print("You entered:", number)
The loop continues until the user enters 0.
At that point, break terminates the loop.
10. Using else in Loops
Python allows an else block to be associated
with both while and for loops.
The else block executes when the loop finishes
normally, without being terminated by break.
Syntax
while condition:
statement(s)
else:
statement(s)
11. Example: else with a while Loop
count = 1
while count <= 3:
print(count)
count = count + 1
else:
print("Loop completed")
Output
1
2
3
Loop completed
The loop ends normally when the condition becomes false.
Therefore, the else block executes.
12. What Happens When break is Used?
count = 1
while count <= 5:
if count == 3:
break
print(count)
count = count + 1
else:
print("Loop completed")
Output
1
2
The loop is terminated by break when
count becomes 3. Therefore, the
else block does not execute.
else in a loop means:
"the loop completed normally",
not simply "the condition became false at some point."
13. Normal Completion vs break
| Situation | Does the loop stop? | Does else execute? |
|---|---|---|
| Loop condition becomes false | Yes | Yes |
break is executed |
Yes | No |
Condition never becomes false and no break |
No — infinite loop | No |
14. Practical Example: Searching for a Number
A while loop with else can be useful
when searching for a value.
numbers = [10, 20, 30, 40, 50]
target = 30
index = 0
while index < len(numbers):
if numbers[index] == target:
print("Number found!")
break
index = index + 1
else:
print("Number not found.")
If the target is found, break terminates the loop
and the else block is skipped.
If the loop reaches its normal end without finding the target,
the else block executes.
15. while Loop vs for Loop
| Feature | while Loop |
for Loop |
|---|---|---|
| Control | Usually controlled by a condition. | Usually iterates over a sequence or iterable. |
| Number of repetitions | Often not known in advance. | Often determined by the iterable or range. |
| Common use | Repeat while a condition remains true. | Process items or repeat over a known range. |
| Infinite loop possibility | Common if the condition never becomes false. | Usually requires a deliberately unbounded iterable or other special construction. |
16. Common Errors with while Loops
Error 1: Forgetting to Update the Variable
count = 1
while count <= 5:
print(count)
Problem: count never changes,
so the condition remains true.
Error 2: Updating in the Wrong Direction
count = 5
while count >= 1:
print(count)
count = count + 1
Here, the loop condition requires count to decrease,
but the program increases it.
Error 3: Incorrect Indentation
Python uses indentation to define the body of a loop.
while count <= 5:
print(count)
count = count + 1
17. Classroom Activity: Trace the Loop
Study the following program and determine its output:
x = 2
while x <= 10:
print(x)
x = x + 2
else:
print("Done")
Answer these questions:
- What is the initial value of
x? - How much does
xincrease each time? - How many times does the loop body execute?
- Why does the
elseblock execute? - What would happen if the update statement were removed?
18. Think About It 🤔
-
Why is a condition necessary in a
whileloop? - What happens if the condition is always true?
- Why can an infinite loop sometimes be useful?
-
What is the purpose of
break? -
When does the
elseblock of a loop execute? -
What is the difference between a loop ending normally and
ending because of
break?
19. Key Terms
| Term | Meaning |
|---|---|
while loop |
A loop that repeatedly executes while its condition is true. |
| Iteration | One execution of the body of a loop. |
| Infinite loop | A loop that does not terminate because its condition never becomes false or because it is intentionally unbounded. |
break |
A statement that immediately terminates the nearest enclosing loop. |
else in a loop |
A block that executes when the loop completes normally,
without executing break.
|
| Condition |
An expression that evaluates to True or
False and controls a while
loop.
|
20. Chapter Recap
-
A
whileloop repeats a block of code while a condition is true. - The condition is checked before each iteration.
- A loop variable often needs to be updated so that the loop can eventually terminate.
- An infinite loop occurs when the loop does not reach a terminating condition.
-
while Truecan be used to create an intentionally continuous loop. -
The
breakstatement immediately terminates a loop. -
The
elseblock associated with a loop executes when the loop completes normally, withoutbreak.
21. Homework 📝
-
Define a
whileloop and write its syntax. -
Write a Python program to print the numbers from
10 to 1 using a
whileloop. - What is an infinite loop? Give one example.
-
Explain the purpose of the
breakstatement. -
Explain when the
elseblock associated with a loop is executed. -
Write a Python program that prints the even numbers from
2 to 20 using a
whileloop. -
Write a program that repeatedly accepts numbers from the
user and stops when the user enters
0.
22. Quick Assessment
-
What is a
whileloop? -
When does a
whileloop stop? - What is an infinite loop?
-
What is the purpose of
break? -
When does
elseexecute with a loop? -
What happens to the loop's
elseblock whenbreakis executed? -
Write a Python program to print numbers from 1 to 5 using
a
whileloop.