Programs with Structure
Loops that count
Work out what values a counting loop's variable takes, and how many times its body runs.
A counting loop does two things at once. It repeats whatever is written underneath it, and while it does so it hands you a variable holding a different number each time round — the counter. That counter is an ordinary variable in every way except one: you do not set it yourself, the loop does. Where the counter starts and where it finishes is written in the loop's own heading, in the brackets after the word range, as two numbers with a comma between them.
The second number is where it stops, not where it ends
This one detail causes more wrong answers than everything else about loops put together, so it is worth being blunt about. The first number in the brackets is the counter's first value, and the counter does get it. The second number is where the counting stops — the loop keeps going while the counter is below it, and the counter never actually takes that value at all. So the last value the counter takes is one below the second number, and the number of trips round is the second number take away the first. Both numbers are always written out in this course, so you never have to guess where a loop begins.
Worked example
What does this print? for n in range(3, 7): print(n)
The counter starts at the first number in the brackets, so the first time round n is 3, and 3 is printed.
The first number is taken exactly as written. Nothing is added to it and nothing is skipped.
Try it together
Now trace this one together: total = 0, and then for n in range(4, 8): total = total + n
Take the counter's values first, and only then the total.
1.What is the first value the counter n takes?
Have a go
Have a go on your own. How many times does the body of this loop run? for n in range(12, 18): print(n)
Ready to practise?
Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.