2.11 Loops
We use a loop to repeat some action or set of actions while a condition is true.
2.11.1 while
Suppose we want to know the sum of the positive integers less than or equal to 5. This is not much work for you to type and compute directly.
1 + 2 + 3 + 4 + 5
15
Now suppose you want the sum of the positive integers less than or equal to 500. That’s
certainly more than you or I would want to type! We can do it easily with a while
loop.
sum, count = 0, 1
while count <= 500:
sum += count
count += 1
sum
125250
We initialize sum
and count
and then increment
sum
by count
and count
by one while count
is less than or equal to 500.
Exercise 2.16
What does Python do if you forget to include count +=
1
?
Let me make the problem smaller and insert a print call so we can see what is happening.
sum, count = 0,...