How to Control Loop Execution in Python: Restart, Skip, and Exit
This guide explores the essential techniques for controlling loop execution in Python. You'll learn how to restart a loop's iteration, skip specific iterations, and exit loops prematurely, using continue
, break
, and conditional logic within while
and for
loops. We'll also cover common patterns like looping until a list is empty.
Restarting a Loop Iteration with continue
The continue
statement skips the rest of the current iteration of a loop (for
or while
) and proceeds to the next iteration.
a_list = [1, 2, 3, 4, 5]
for num in a_list:
if num % 2 == 0: # If the number is even...
continue # ...skip to the next iteration
print(num) # Only odd numbers will be printed
Output:
1
3
5
continue
is used to skip parts of the loop, not to go back to a previous index of the iterable.
Exiting a Loop with break
The break
statement exits the innermost enclosing for
or while
loop entirely.
a_list = [1, 2, 3, 4, 5]
for num in a_list:
if num > 3:
break # Exit the loop when num is greater than 3
print(num)
Output:
1
2
3
- The loop terminates once the value of
num
is greater than 3.
Looping Until a List is Empty
A common pattern is to process items in a list until the list is empty. This uses a while
loop and the pop()
method:
my_list = ['tutorial', 'reference', 'com']
while my_list: # Loop while the list is NOT empty (truthy)
item = my_list.pop(0) # Removes and returns the first element
print(item)
print(my_list) # Output: [] (empty list)
Output
tutorial
reference
com
- Using
my_list
in a while loop means that for as long as it's not empty, it will evaluate to True and continue to execute. my_list.pop(0)
removes and returns the first element of the list. If you usemy_list.pop()
(without an index), it removes and returns the last element.
Looping with Multiple Conditions
You can combine multiple conditions in a while
loop using and
, or
, and not
:
my_list = ['tutorial', 'reference', 'com']
count = 10
while my_list and count > 0: # Loop while list is NOT empty AND count > 0
my_list.pop()
count -= 1 # Decrement count
print(my_list) # Output: []
- The and keyword requires both
my_list
to contain elements, and for thecount
variable to be greater than zero.
Looping Over an Empty List
If you attempt to loop over an empty list, the loop body won't execute. To avoid unexpected errors, you can use my_list or []
to provide a fallback list:
my_list = None # can be None, or an empty list, or any other falsy variable
for item in my_list or []: # Or statement will handle empty list gracefully
print(item) # This will not run if `my_list` is None or empty.
- The
or
keyword takes advantage of the truthiness of the list - empty lists are falsy.
Simulating a Loop Restart (Advanced)
There is no direct "restart" command for a loop in Python that would go back to a specific index. The closest equivalent is to use a while
loop and carefully manage your loop control variable:
import random
num = 1
a_list = []
while num < 5:
if random.uniform(0, 1) > 0.5:
num += 1
a_list.append(num)
else:
a_list.append(num)
num = 1 # Reset 'num' to 1, effectively "restarting" the loop's logic
print(a_list)
print(num) # Output: 5 (because the loop only exits when num >= 5)
- This is not restarting the loop in the sense of
continue
orbreak
. It's resetting the conditions that control the loop's progression, so that it starts checking the while condition from the start.