while
A while loop tests, runs its block, and tests again
Test, block, test again. Something must change.
A while loop repeats its block for as long as a condition holds. Follow n. n is three. Greater than zero is True, so it prints three, and n drops to two. Two: still True. It prints two. One: True. It prints one, and n becomes zero. Zero greater than zero is False, so the loop ends. Only now does the next line run, and print go.
while · Going deeper
Sentinels and the walrus operator
A sentinel means stop. := assigns inside an expression.
for
for takes each item in turn and gives it a name
for name in sequence. Once per item.
A for loop walks through a sequence. You name a variable, and it is given each item in turn. First n is four, and total becomes four. Then n is seven: total, eleven. Then n is two: total, thirteen. The list is used up, so the loop ends and thirteen is printed.
for · Going deeper
What you can loop over
str, list, tuple, range. Not an int.
Check yourself
What does this print?
range()
range stops before its stop
range(start, stop, step). The stop is never included.
Range produces a run of whole numbers for a loop to walk through. Range five gives five numbers, nought to four. Five itself is left out. With two arguments, the first is where to start. A third argument is the step: one, four, seven. Ten is the stop, and is left out. A negative step counts down: five, three, one. Zero is the stop, so the run ends before it.
range() · Going deeper
More ranges
The wrong way round is empty, not an error.
break, continue, pass
break leaves the loop. continue skips to the next turn.
continue: next turn. break: out of the loop.
Two keywords change the course of a loop from inside it. One is printed. Two is printed. At three, continue skips the rest of this turn. Nothing is printed. Four is printed. At five, break ends the whole loop. So six is never reached. The output is one, two, four.
break, continue, pass · Going deeper
pass, while True and infinite loops
pass does nothing. while True needs a break.
Check yourself
What does this print?
Nested loops
The inner loop runs in full for every outer turn
Outer once, inner all the way. Then outer again.
A loop can contain another loop. The outer loop sets r to zero. The inner loop starts: c is zero. c is one. c is two. The inner loop is finished. Now r moves to one, and the inner loop starts over from zero. One, one. One, two. Two turns of three: six prints in all.
Nested loops · Going deeper
Two more nested patterns
A break ends only the inner loop.
Check yourself
What does this print?
Lesson complete
You finished “Loops: while, for and range”
Answer the questions along the way to see your score here.