menu EXPLORE
history NEW

While Loop in Python

Loop while It is a control flow structure widely used in most programming languages ​​along with the loop for .

In Python, the statement while It is less used than in other programming languages ​​such as Java or C++. However, it is important to know how it works and understand in which cases it is useful to apply it in our code.

How the while statement works in Python

What this type of loop does is check if a certain condition exists. If so, the part of code inside the while . When it's finished, check it again. If the condition is met, it re-enters the loop.

On the contrary, if it is not fulfilled, the loop is exited. while and the code continues to run. Let's see an example.

The most common example of code in which the while It is very helpful when we program a counter that we want to count from 1 to 10.

Let's look at the code and then we will explain what each line means:

  • The first step is to declare the number variable as an integer. We set the value to 0 since from here we will go up until we reach 10.
  • Next we write the sentence while . The second line tells us that as long as the number variable is less than 10 then the loop has to be executed.
  • The third line of code prints the value of the number to the screen.
  • For the last one, number += 1 what it does is add 1 to the number that is stored in the variable. If we did not do this, the numerical variable would always be zero and therefore we would have an infinite loop since the condition that the variable has to be less than 10 would be fulfilled forever.

Break and continue statements inside while loops

The reserved words break and continue They allow us in Python (and other programming languages) to have finer control of what happens inside the loop.

The break statement is used to stop and exit the loop. Let's look at a practical example:

This code, when the number is equal to 5, will stop executing. Therefore, this little program will only print numbers from 0 to 4.

Instead, the ruling continue What it does is that the rest of the code is not executed and the loop starts again while . Let's see how it looks in code:

When the numeric variable reaches 5 the loop will start again without executing the part where the variable is printed. In this case we have written the statement number += 1 before the conditional since otherwise, when the variable reaches 5, the variable will never be updated and we would have an infinite loop.