While Loop in Python

Parth Patel
3 min readOct 22, 2021

It is irritating to do the same task again and again hence programmers tend to use loops in coding. Today we will learn the while as part of Python Loops.

hackr.io

The while Loop

With the while loop, we can execute a set of statements as long as a condition is true.

Example: Print i as long as i is less than 3:

Code:

A simple example for a while loop
Output for above code

Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example, we need to define an indexing variable, i, which we set to 1.

The break Statement

Using break we can terminate or stop the execution of a loop.

Example: Exit the loop when i is 5

output

As we can observe that we have put the condition to execute the loop until i become 8 but we are stopping the execution of the loop when i==5 using the break statement.

The continue Statement

Continue statement is used when we need to skip execution of a particular step when it meets the given condition.

Example: Continue to the next iteration if i is 3:

As shown in the above example that we are printing from 1 to 8 but don’t want to print 5 so we have our condition and continue the statement to skip execution when i=5.

The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

Example: Print a message once the condition is false:

Thanks to all for supporting me and reading my articles. Hope you like it. Please share it with your friends as well because “Sharing knowledge is the most fundamental act of friendship. Because it is a way you can give something without losing something.”Richard Stallman

Thank you 😄😄

--

--