Break and continue
Break and continue
Sometimes it is useful to interrupt the flow of a loop. Python provides two statements for this purpose: break and continue which can be used in both while and for loops.
Break
Concept: break
The break statement can be used to exit a loop before the loop condition is False in a while loop, or before the loop has iterated over all items in a for loop.
while True:
command = input("Enter a command (or 'exit' to quit): ")
if command == "exit":
breakConsider a script that requires the user to enter a password (like the sudo command in Linux). The script should allow the user to enter the password three times before it exits.
We could of course create a variable to indicate whether the user has entered the correct password, and use that variable in the while loop condition. While this works, it is not very elegant. A better solution is to use the break statement to exit the loop when the user enters the correct password.
import sys
correct_password = "S3cret"
attempts_left = 3
while attempts_left > 0:
password = input("Password: ")
if password == correct_password:
print("Access granted")
break
attempts_left -= 1
print(f"Wrong password, {attempts_left} attempt(s) left")
if attempts_left == 0:
print("Account locked")
sys.exit(1)
# Do something that requires the user to be authenticatedContinue
Concept: continue
The continue statement can be used to skip the rest of the code in the current iteration of a loop and move on to the next iteration.
This can be useful when certain cases must be skipped. Say you want to update the default shell of all users on a system, but you want to skip any user with the nologin shell. You could use a continue statement to skip those users and continue with the next user.
for i in range(100):
# Skip even numbers
if i % 2 == 0:
continue
print(i)Consider a script that needs to check the open ports on each device in a network, but should skip any devices that are not reachable. Since we know the possible IP addresses of the devices, we can use a for loop to iterate over the list of IP addresses and check each one. If the device is not reachable, we can use the continue statement to skip the rest of the code in the loop and move on to the next device.
The following code does not run, it is illustrative. Later we'll discuss how to check if a host is reachable and how to retrieve the open ports on a host.
for i in range(1, 255):
if not host_is_reachable(f"192.168.1.{i}"):
continue
open_ports = get_open_ports_for_host(f"192.168.1.{i}")break vs continue
break | continue | |
|---|---|---|
| Purpose | Leaves the loop. Nothing after it in the loop body runs, and no further iterations happen. | Leaves the current iteration only. The loop carries on with the next item or the next test. |