while

A while loop tests, runs its block, and tests again

n = 3while n > 0: print(n) n -= 1print('go')nn > 0printsthen n is3True322True211True100Falsethe loop endsthen print('go') runsA while loop tests, runs its block, and tests again.The test comes first, so the block may run no times at all. Something inside the block mustchange what the test looks at. Here n -= 1 does. Without it the loop never ends.

Test, block, test again. Something must change.

while · Going deeper

Sentinels and the walrus operator

A sentinel: a value that means stoptotal = 0x = int(input())while x != 0: total += x x = int(input())print(total)The same, with the walrus operatortotal = 0while (x := int(input())) != 0: total += xprint(total)The user types 4, 5, 0. Both print 9.:= assigns a value and hands it on in the same expression.x := int(input()) reads a number, names it x, and gives that number to the != test. It savesrepeating the input line. The brackets are needed: without them x would get the result ofthe comparison. A loop that never reaches its sentinel is an infinite loop.

A sentinel means stop. := assigns inside an expression.

for

for takes each item in turn and gives it a name

total = 0for n in [4, 7, 2]: total += nprint(total)472n is 4total 4n is 7total 11n is 2total 13prints 13for takes each item in turn and gives it a name.There is no test to write and no counter to update. The loop runs once for each item, inorder, and stops when they run out. After the loop, n still holds the last item.

for name in sequence. Once per item.

for · Going deeper

What you can loop over

Loop overEach turn getsExample outputfor ch in 'cat':one characterc, a, tfor x in [4, 7, 2]:one item of the list4, 7, 2for x in (4, 7, 2):one item of the tuple4, 7, 2for i in range(3):the next number0, 1, 2for x in []:nothing: the block never runs(none)for x in 5:TypeError: an int is not iterableAnything you can loop over is called iterable.Strings, lists, tuples and ranges are sequences: they have an order, and for follows it.To repeat something five times, loop over range(5), not over 5.

str, list, tuple, range. Not an int.

Check yourself

n = 10while n > 4: n -= 3print(n)

What does this print?

range()

range stops before its stop

012345678910range(5)range(2, 6)range(1, 10, 3)range(5, 0, -2)a value the range givesthe stop: never givenrange stops before its stop.range(5) is five numbers, 0 to 4. range(2, 6) starts at 2. A third argument is the step,and a negative step counts down: the stop is still left out.

range(start, stop, step). The stop is never included.

range() · Going deeper

More ranges

CallGivesHow manyrange(5)0, 1, 2, 3, 45range(2, 6)2, 3, 4, 54range(1, 10, 3)1, 4, 73range(5, 0, -2)5, 3, 13range(10, 0, -3)10, 7, 4, 14range(-2, 2)-2, -1, 0, 14range(3, 3)(nothing)0range(5, 0)(nothing)0One argument is the stop. Two are start and stop. Three add the step.A range going the wrong way is empty, not an error: range(5, 0) gives nothing. The argumentsmust be whole numbers, and a step of 0 is a ValueError. print(range(3)) shows range(0, 3);use list(range(3)) to see the numbers.

The wrong way round is empty, not an error.

break, continue, pass

break leaves the loop. continue skips to the next turn.

for n in range(1, 7): if n == 3: continue if n == 5: break print(n)1prints 12prints 23continueskipped4prints 45breakloop ends6never reachedbreak leaves the loop. continue skips to the next turn.continue abandons the rest of this turn and goes back to the top for the next item.break abandons the whole loop: 6 is never looked at. The output here is 1, 2, 4.

continue: next turn. break: out of the loop.

break, continue, pass · Going deeper

pass, while True and infinite loops

pass: do nothingfor n in range(3): passprint(n)prints 2while True, with breakn = 0while True: n += 2 if n > 5: breakprint(n)prints 6An infinite loopn = 3while n > 0: print(n)prints 3 for everpass fills a block that must exist but has nothing to do.A block cannot be empty, so pass is the placeholder. It does not skip or stop anything.while True never ends by its test, so it needs a break. A loop whose variable is neverupdated is the accidental kind.

pass does nothing. while True needs a break.

Check yourself

for n in range(5): if n == 2: continue if n == 4: break print(n)

What does this print?

Nested loops

The inner loop runs in full for every outer turn

for r in range(2): for c in range(3): print(r, c)c = 0c = 1c = 2r = 0r = 10 0turn 10 1turn 20 2turn 31 0turn 41 1turn 51 2turn 6The inner loop runs in full for every turn of the outer loop.The outer loop sets r to 0, and the inner loop goes through all 3 values of c. Only thendoes r move to 1, and the inner loop starts again from 0. 2 turns of 3 is 6 prints.

Outer once, inner all the way. Then outer again.

Nested loops · Going deeper

Two more nested patterns

The inner range can depend on the outerfor i in range(1, 4): for j in range(i): print(i, end='') print()122333break leaves only the loop it is infor i in range(3): for j in range(3): if j == 1: break print(i, j)0 01 02 0Trace a nested loop with one row per turn of the outer loop.On the left, the inner loop runs i times, so each row is one digit longer. On the right, thebreak ends the inner loop at j = 1 each time, and the outer loop carries on to its next turn.

A break ends only the inner loop.

Check yourself

count = 0for i in range(3): for j in range(2): count += 1print(count)

What does this print?

Lesson complete

You finished “Loops: while, for and range”

Answer the questions along the way to see your score here.

Open in a new tab