break, continue, and Nested Loops

Two keywords let you steer a loop from inside it:

break, stop the loop entirely, right now

continue, skip the rest of this pass, move to the next item

Both work identically in Python and JavaScript, spelled the same way.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Change the name you're searching for to someone who isn't in the list. Then add a variable that remembers whether the name was found, and print "Not found" after the loop when it wasn't.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Change it to skip every multiple of 3 instead, so it prints 1, 2, 4 and 5.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

A loop inside a loop is a nested loop. The inner loop runs completely for every single pass of the outer one, three outer passes × two inner passes is six total runs. Powerful, and worth respecting: nesting multiplies the work.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Two by two gives four lines. Add a third level and a third language, then add a counter that prints how many combinations there are once both loops finish.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

◈ Graded Challenge

Loop over the hours list to create total_hours holding the sum, and busy_count holding how many entries are over 50. Use the accumulator pattern, not addition by hand.

Name it exactly: total_hours, busy_count

2 visible + 1 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back