Coding for All
Lesson 21: Break
Break Escape from a loop with break.
1count = 0
2while True:
3 print(count)
4 count = count + 1
5 if count == 5:
6 break
Terminal
$ python3 main.py
0
1
2
3
4
Every line, explained
count = 0
This creates a variable: a named box that stores a value. In Python you just write name = value: the = stores the value on the right into the name on the left. No special type word, no semicolon; Python keeps it simple.
while True:
A while loop repeats its indented body for as long as the condition is True. The condition is checked again before every trip around the loop. while True: would repeat forever, because the condition is always True! We will need break to escape.
print(count)
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets.
count = count + 1
Adds 1 to count each trip around the loop.
if count == 5:
if checks the condition after it. Two things to notice: the line ends with a colon :, and the lines that belong to the if are indented 4 spaces underneath. Python uses indentation to know exactly which code is "inside" the if. If the condition is True the indented code runs; otherwise Python skips it. (The editor indents for you here; in a real editor you would type the 4 spaces.) Once count reaches 5, it is time to stop. Notice this if is inside the loop, so its body is indented twice.
break
break immediately stops the loop it is inside; Python jumps to the first line after the loop. Without it, this while True: loop would run forever.