3.1 while Loops
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.
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.
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.
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. This is the first time we use a module here: import random imports the module, and random.randint(1, 100) creates a random integer from 1 to 100. Modules are introduced more 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 is what exits when the user guesses correctly.