The while Loop
Imagine you need to print the numbers from 1 to 100. You could write print() a hundred times, but it would take ages, and changing anything later would be even worse. Programs repeat work like this all the time: they go through every student in a list, check every product in a shop, or redraw a game screen 60 times a second. That is what loops are for. A loop is a piece of code that runs again and again.
The simplest loop is while. It repeats a block of code while its condition is true:
number = 1
while number <= 5:
print(number)
number += 1This prints:
1
2
3
4
5A while loop looks like an if: the keyword, a condition, a colon and an indented block of code. The difference is that if runs its block at most once, but while keeps coming back to the condition. Step by step:
- The program creates
numberwith the value1. - It checks the condition
number <= 5. It isTrue, so it runs the block: it prints1, andnumber += 1increasesnumberto2. - It goes back to the condition.
2 <= 5is stillTrue, so it prints2and increasesnumberto3. - And so on, until
numberis6. Then the condition isFalse, the loop ends and the program continues with the code after the loop.
Each run of the block is called an iteration. This loop has five iterations. To print the numbers up to 100, you would only change 5 to 100.
Which lines belong to the loop? Just like with if, the indented ones. A line below the loop that isn't indented runs only once, after the loop has finished:
number = 1
while number <= 3:
print(number)
number += 1
print("Done")1
2
3
DoneWatch out for loops that never end. If you forget the line number += 1, or don't indent it (so it's after the loop), number stays 1, the condition is always true and the loop prints 1 forever. This is called an endless loop (or an infinite loop). In these exercises, such a program is stopped after 5 seconds with the message The program ran too long and was stopped. Does it have a loop that never ends? When you see it, check that the loop changes the variable in its condition, so that the condition becomes false at some point.
Instructions
- 1
Create a variable
numberwith the value10. The loop will count with it. - 2
Below it, write a
whileloop that runs whilenumberis less than or equal to20. Inside the loop, printnumberand then increase it by 1. The program prints the numbers from 10 to 20, each on its own line. - 3
Now change one number in your code so that the loop prints all the numbers from 10 to 100.