Working with While Loop in Python

In Python, While Loops is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance.

Syntax:

while expression:
    statement(s)

Here are Few Differences Between While Loop in Python and While loop in R Language:

  1. R is a Vectorized Programming language and here there are lot of operations That we perform on Analytics, Data Mining & Visualization

The Things in R are done in Vectorized approach and that is the great advantage which will allow you to avoid creating Loops all the time. As we can apply some functions and Vectorized approach to achieve the things in R language .

2. Where as Python is a Object oriented Programming language . Here we don’t have a Luxury of working with Vectors, although we have many other advantages that we will be going through them in the upcoming Posts.

I will be demonstrating below how the while loop works in python :

Here False is an Expression and Printing “Hello” is a block of statements.

In any other programming Language, The while Loop is Constructed in such a way that First It checks the condition/Expression by Open Curly braces and If Condition is true, it will go through the curly braces and execute the Block of statements within the braces and Complete its action, But in Python The while Loop is structured in a different way : In Python we don’t use any Curly or Open Braces to Execute the block of statements , We Use Tabulation and indentation to execute the Expression and Block of statements.

From the above example ; False is an condition/ Expression, If Condition is True it prints the next Block of statements, But here The condition is False so It is Not printing anything else and The Print statement Indentation started from fourth Place , This tells Python that Print Statement is considered as Block of statements.

By Looking at the indentation we can Identify that when While Loop starts and when The Body of the while loop starts and when while loop Ends.

Let’s check while Loop for true Condition:

Here The Expression/Condition is true so It is Printing the Hello Infinite Times, This is going to a Infinite Loop, to stop the Infinite Loop Click on 0 Twice(Click on Zero twice from your Keyboard). This will stop the Infinite Loop execution.

Click on restart Button To restart the Kernel.

Will Work on Quick Example to check how the block statements works :

Output : Run the cell

Hope We are clear with how to use while statement in Python. Keep Coding 👍