While can be very useful in some cases. You shouldn’t avoid it just because it can cause an infinite loop, but you should avoid it when it’s not the correct thing to use.
When working with a stack while is important. You want to keep going until you’ve processed the entire stack (which might grow while the loop is working). A good example of this is a flood fill:
def fill(canvas, mouse_position):
current = mouse_position
stack = [current]
while stack:
x, y = stack.pop()
current_tile = current_dict.get((x, y))
if current_tile.empty:
current_tile.empty = False
search_array = [(-1, 0), (0, -1), (1, 0), (0, 1)]
for n in search_array:
nx, ny = n
stack.append((x + nx, y + ny))
mouse_position = (5, 12)
fill(canvas, mouse_position)
In all cases you should make sure that either there is a natural limit to the stack size (in a flood fill it would be the edge of the canvas) or add an counter to stop the loop if it goes on too long.
Recursion in python is a kind of stack and while loop:
def add_to_list(number_list, current):
current += 1
if current < 1000:
if current%2==0: # if the number is even, keep it
number_list.append(current)
add_to_list(number_list, current)
number_list = []
add_to_list(number_list, 0)
There are other uses for the while loop, such as solving a problem (packing rectangles in to a grid, maze navigation, etc…) through brute force.
Most often it is used where you can’t use a for loop because the contents of the list can change during the operation.
If the list remains the same then the best practice is to use a for loop. If you want the operation to carry on over several ticks then you should use an index counter or pop items from the start of the list.