pass, break, continue
pass
pass
is a simple statement that simply does not do anything.
It is useful as a placeholder, especially when you need to have an indented block in a compound statement like if
and for
but are not ready to write your code.
words = ["be", "very", "quiet"]
for word in words:
pass
Altering the flow of loops
In (strict) structured programming, there is a rule that each block
must have only one entry point and one exit point,
[**put road illustration here**]
This prevents programmers from arbitrarily ‘jumping’ to different lines in code. This was usually done with a goto
statement in the good old days (probably before many of you were born!) This made it hard to read, understand and debug codes.
However, sometimes it is easier to allow the programmer to alter the flow of a loop, for example exiting the for
-loop earlier if some conditions are met. Two simple statements break
and continue
allow this.
break
The break
statement will force the program to exit a loop, terminating the loop containing it.
Here is a possible use case (what does it do?)
while True:
line = input("> ")
if line == "done":
break
print(line)
print("Done!")
And another example (guess what it does):
target = 3
items = [1, 5, 3, 2, 1, 7, 6]
for (i, item) in enumerate(items):
if item == target:
print(f"The number {item} found at index {i}!")
break
Exercise: Of course, we can write the programs above without any break
statements. How? Try it yourself first before peeking at my answer at the end of this page!
There are, however, times when having the break
statement can make your code more readable. For example, you can use break
statements can be useful to get out of very very deep nested loops.
continue
The continue
statement also alters the flow of control, but instead of exiting the loop, it skips any instructions after it (inside the loop) and jump straight back to the condition check (the beginning of the loop).
Here is an example: (as usual, try to understand what the code does)
numbers = [1, 4, 3, 4, 8, 9, 7, 6, 3, 2]
for number in numbers:
if number % 3 == 0:
continue
print(number)
And the answer to the earlier task…
Here is how I implemented the code from earlier without the break
statement (strictly structured program)
target = 3
items = [1, 5, 3, 2, 1, 7, 3, 6]
found = False
found_index = -1
i = 0
while i < len(items) and not found:
if items[i] == target:
found = True
found_index = i
i = i + 1
if found:
print(f"The number {target} found at index {found_index}!")