Loops
“Write the first 100 numbers.”
There are several assumptions implicit in this seemingly simple command. The first is that the student knows where to start, namely at number 1. The second assumption is that the student knows where to end, at number 100. And the third is that the student understands that they should count by 1.
In programming, this set of instructions may be executed with a loop.
There are three key components to most loops:
- The start of the loop
- The end of the loop
- The increment between numbers in the loop
Python distinguishes between two fundamental kinds of loops: while
loops and for
loops.
while loops
In a while
loop, a designated segment of code repeats, provided that a particular condition is true. When the condition evaluates to false, the while
loop stops running. A while
loop may print out the first 10 numbers.
You could print the first 10 numbers by implementing the print
function 10 times, but using...