Loops repeat a block of code. A while loop checks a condition first. As long as the condition is True, Python runs the loop body, then goes back and checks the condition again.
Basic while structure
A stable while loop usually has three parts:
- Initial value: prepare the loop variable before the loop starts.
- Condition: decide whether the loop should continue.
- Update: change the loop variable inside the loop.
i = 1 # initial value
while i <= 5: # condition
print("In loop: i =", i)
i += 1 # update
print("After loop: i =", i)Output:
In loop: i = 1
In loop: i = 2
In loop: i = 3
In loop: i = 4
In loop: i = 5
After loop: i = 6A while loop checks before it runs. That means the loop body may run many times, or it may run zero times.
Step through a while loop
Execute the program one line at a time. The blue line is next; variables and output update on the right.
01i = 10203while i <= 5:04 print("In loop: i =", i)05 i += 10607print("After loop: i =", i)
>>>
KNOWLEDGE QUIZ
Accumulation and averages
Loops often work with an accumulator variable. The program below reads the heights of 5 people and computes the average height.
NUM_PEOPLE = 5
total = 0
i = 1
while i <= NUM_PEOPLE:
height = float(input("Enter person %d's height: " % i))
total += height
i += 1
average = total / NUM_PEOPLE
print("Average height: %.2f" % average)One possible run:
Enter person 1's height: 160.8
Enter person 2's height: 175.2
Enter person 3's height: 171.2
Enter person 4's height: 181.3
Enter person 5's height: 164
Average height: 170.50total += height adds the current height into the accumulated total. After the loop ends, total stores the sum of all heights.
KNOWLEDGE QUIZ
Looping until a condition changes
while is useful when the number of repetitions is not known immediately. For example, you can count how many digits an integer has.
num = abs(int(input("Enter an integer: ")))
if num == 0:
digits = 1
else:
digits = 0
while num != 0:
num //= 10
digits += 1
print("Digits:", digits)One possible run:
Enter an integer: 123
Digits: 3The program handles 0 separately. If you only write while num != 0, the loop will not run for input 0, and the digit count would incorrectly become 0.
KNOWLEDGE QUIZ
Number guessing game
Another common while scenario is when the program does not know how many attempts the user will need. A number guessing game is a classic example. The program first creates a random answer, then keeps reading guesses. If the guess is too high, it prints a hint; if the guess is too low, it prints a different hint; when the guess is correct, break exits the loop.
random is Python's random-number module. import random imports it, and random.randint(1, 100) creates an integer from 1 to 100. Modules are introduced systematically in Chapter 6.
import random
answer = random.randint(1, 100)
cnt = 0
while True:
num = int(input("Guess a number: "))
cnt += 1
if num > answer:
print("Too high")
elif num < answer:
print("Too low")
else:
break
print("Correct! You guessed %d time(s)." % cnt)One possible run:
Guess a number: 50
Too high
Guess a number: 25
Too low
Guess a number: 37
Too low
Guess a number: 43
Too high
Guess a number: 40
Too high
Guess a number: 38
Too low
Guess a number: 39
Correct! You guessed 7 time(s).Here, while True creates a loop whose condition always looks true. It does not stop by itself; the break inside the loop exits when the user guesses correctly.
Actually play the guessing game
A random answer is chosen from 1–100. Use the hints to shrink the blue candidate range; when you guess correctly, watch break end the loop.
01answer = random.randint(1, 100)02while True:03 guess = int(input("Your guess: "))04 if guess == answer:05 print("Correct!")06 break07 elif guess > answer:08 print("Too high")09 else:10 print("Too low")
>>>
Use while to compute a reciprocal sum
Read a positive integer n and use while to compute 1 + 1/2 + 1/3 + ... + 1/n.
- Read a positive integer n.
- Use a while loop to accumulate each 1/i term.
- Print the final sum with two decimal places.
Use while to sum the digits of an integer
Peel off the digits of a positive integer and add them together.
- Read a positive integer named num.
- Use a while loop to take the last digit and add it to sum_digits.
- Print the digit sum after the loop ends.