Loops in Python

Loops in Python are a way to repeat an operation any number of times. There are different kinds of loops that are used depending on whether you want an operation to be performed a specific number of times, or if you want the operation to be repeated until a specific condition is met.

When we want to repeat an operation or sequence, we use a loop. With the help of the loop, we can write a program sequence (e.g., a calculation) to be performed while either a particular condition is fulfilled (conditional loop), or a loop that repeats the program sequence a predetermined number of times (counting loop).

 

The three most common structures for repetition within Python that we will, of course, look at more closely are:

  • While loop
  • For loop

HOW DOES A LOOP IN PYTHON WORK?

We can illustrate a loop using the flow chart on the right that shows in a simple way how loops work.

 

1. The program sequence begins at Start and then checks if the condition is met

 

2. If the condition is met ( Yes ) then the operation is performed, if the condition is not met ( No ) then the program moves on

 

3. The loop then repeats the process and returns back to check if the condition is met

Loops in Python

Note that we can end up with so-called “infinity loops“, that is, loops that do not proceed in the program (terminated / finished). The condition in the loop is simply never met, and since the condition must be fulfilled for the loop to complete, it runs on. Fortunately, the compiler shuts down the program and gives you an error message, so there’s nothing you need to worry about. It is also good to know that it is fairly simple (and common) error to do.