While Loops in Python
How to use while loops in Python
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:
‘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:
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:
Conclusion
In this tutorial, we understood as to how a while loop works along with break, continue and else statements.