While Loops in Python

How to use while loops in Python

Vidya Menon
The Startup
2 min readOct 8, 2020

--

Photo by David Streit on Unsplash

In this tutorial we will learn how to use while loops in Python.

What is a loop?

Loops are generally a block of code which you want to repeat a fixed number of times or until a certain condition is met. Python has two loop commands. They are :

  • while loops
  • for loops

Now let’s take a closer look at while loops and how they function.

While Loops

While loops are used to execute a set of statements as long as the specific condition is true. The loop terminates immediately when the condition becomes false.

Syntax for a while loop:

In the example below, we want to print ‘x’ as long as it is less than or equal to 5:

Please note that in the above example, incrementing x is crucial to avoid the loop running infinitely.

‘break’ and ‘continue’ Statements:

These are used to control the loop statements which change the execution of a loop from its normal sequence.

A Break Statement breaks or stops the the loop even if the condition is true whereas a Continue Statement returns the control to the beginning of the loop. Let’s understand these with the help of some examples:

Here, even though x is less than 5, but as soon as it is equal to 3, it breaks out of the loop.
Here, even though x is less than 5, but as soon as it is equal to 2, it skips the statements after this condition and jumps to the next iteration.

Using ‘else’ statement with while:

As we know, while loop executes the block until a condition is satisfied.
The else statement is executed only when the while condition becomes false.
Syntax:

Let’s take a look at an example:

Here, the ‘else’ statement is executed once the ‘while’ condition no longer is true

Conclusion

In this tutorial, we understood as to how a while loop works along with break, continue and else statements.

--

--