When writing FOR or WHILE loops in Python, there are situations where you might want to interrupt the loop so that you don't have to wait for the entire loop script to run - this would be an inefficient use of time and computational resources.
As a result, you frequently find the words break and continue within loops. How do they work?
BREAK
The break keyword is used if, as in the example below, option B is found to be true and we no longer need to check any other conditions in order to carry on executing the rest of the code. Effectively, everything that comes after option B is considered irrelevant if B is true.

For example, when calling an API, you probably want different things to happen depending on the outcome, e.g.: the call was successful, the call received an error, a rate limit was reached so you want the script to wait and try again later.
In this scenario, let's assume the API call was successful (status_code = 200 🎉). At that point, you can do what you need to do, e.g.: query data, download data, etc., but there is no need to loop through every other possible outcome so you can break out of the loop and carry on to execute the rest of the code, like data preparation or analysis.
Example:
while attempts <= max_attempts:
response = requests.get(url, params = payload, auth = (api_key, secret_key), timeout = 30)
status_code = response.status_code
if status_code == 200:
with open(zip_path, "wb") as file:
file.write(response.content)
print(f"Success - {describe_status(status_code)}")
BREAK
----- Everything after this point is ignored if the API call is successful -----
else:
if status_code == 429:
request_minute = datetime.now().strftime('%M')
sleep_minutes = (60-int(request_minute))
sleep_seconds = 60*sleep_minutes
print(f"Limit Exceeded - {describe_status(status_code)}. The request will automatically try again in {sleep_minutes} minutes ")
attempts += 1
time.sleep(sleep_seconds)
time.sleep(10)
elif 300 <= status_code < 500:
print(f"Failed - {describe_status(status_code)}")
break
else:
sleep_seconds = 30*attempts**2
if attempts == max_attempts:
print(f"Failed after {attempts} attempts - {describe_status(status_code)}")
else:
print(f"(Attempt {attempts}/{max_attempts}) Trying again in {sleep_seconds} seconds - {describe_status(status_code)}")
time.sleep(sleep_seconds)
attempts += 1
CONTINUE
The continue keyword is used if we want to restart the loop as soon as a certain condition is found to be true. For example, if option B is true, don't worry about checking option C, go back to the top and start the loop again.

Some examples of where continue is used:
- Skipping comments when reading a file, e.g.: if a line of SQL starts with '--' this indicates that it is a comment; since it isn't "doing" anything, we can interrupt the loop and continue to the next line of SQL code.
- Filtering files by type, e.g.: when processing zip files, we may want to ignore certain file types. Within the loop we can identify those file types to ignore and use continue to restart the loop and check the next file until we find one that is relevant.
- Skipping work that is already done, e.g.: if the loop involves creating or deleting files, these files may already exist or may already have been deleted, in which case we can check for this and continue to restart the loop.
- Validating user input, e.g.: if we require a user to enter a number, but instead they enter a text value, this would likely cause a Data Type error later in the script. To avoid "crashing" things, we can pick this up early on in the loop and use continue to get the user to start again.
- Handling run-time errors. Run-time errors, often called Exceptions, occur when the code encouters something unexpected like FileNotFoundError, when the code is expecting to retrieve a file. Sometimes, we don't want these errors to halt all other processes, so we use continue to ignore the thing that triggered the Exception and restart the loop.
Example:
while attempts <= max_attempts:
try:
# Form API request
response = requests.get(url, params = payload, auth = (amp_api_key, amp_secret_key), timeout = 30)
# Exception block to account for no response or request timeout
except requests.exceptions.RequestException as e:
if attempts == max_attempts:
logger.error(f"Request failed after {attempts} attempts: {e}")
break
else:
logger.warning(f"(Attempt {attempts}/{max_attempts}) Request failed: {e}. Retrying in 30 seconds...")
time.sleep(30)
attempts += 1
CONTINUE
---- The status_code varialbe will only be written after a response is received from the API call. If not response is received, CONTINUE is used to loop back and try again ----
# Record status
status_code = response.status_code
