Unit 2 · While Loop
While Loop
Master indefinite loops using Python's while loop to repeat code as long as a condition remains
true.
Introduction
Loops allow programs to repeat a block of statements multiple times. The while loop is an
example of an **indefinite loop** or condition-controlled loop. It repeatedly runs its block of code as long
as its condition expression evaluates to True.
Table of Contents
Syntax of While Loop
The syntax of a while loop in Python is:
while condition: # Indented block of statements statements
The condition is evaluated first. If it is True, the loop body runs. After executing the body,
the condition is evaluated again. This repeats until the condition becomes False.
Three Key Elements of a Loop
To write a working loop that terminates correctly, we need three key elements:
- Initialization: Setting up a starting value (e.g.,
count = 1). - Condition Check: The test expression used by the loop (e.g.,
while count <= 5). - Update (Increment/Decrement): Modifying the state so the loop makes progress towards
termination (e.g.,
count += 1).
Infinite Loops and How to Avoid Them
If the loop condition is always True and never updated to False, the loop will run
forever, creating an infinite loop.
Warning: An infinite loop can freeze your
program or crash your system. You can force-stop an infinite loop in the terminal by pressing
Ctrl + C.
# Infinite Loop Example (Avoid this!) x = 1 while x <= 5: print(x) # Runs forever because x is never incremented!
Code Examples
Example 1: Printing numbers 1 to 5
count = 1 while count <= 5: print(count) count += 1 print("Done!")
Example 2: Adding user-entered numbers until 0 is typed
total = 0 val = int(input("Enter a number (0 to exit): ")) while val != 0: total += val val = int(input("Enter a number (0 to exit): ")) print("Total sum:", total)
Summary
A while loop executes as long as its condition evaluates to True. Correct
initialization, clear condition checks, and updating variables inside the loop body are required to prevent
programs from entering infinite loops.