Loop While In Python – Detailed Instructions

Until a specified condition returns false, a while loop is used to repeatedly iterate over a block of code. Python’s for loop, which is used for the same thing, was demonstrated in the previous tutorial. The fundamental distinction is that while we use the while loop when we are unsure of how many times the loop needs to run, while we use the for loop when we are absolutely positive.

The while loop’s syntax

while condition:

The body of while is a collection of Python statements that must be run repeatedly. The given condition must return false before this group of statements can stop being executed.

While loop flow

1. The specified condition is checked first, and if it returns false, the loop is stopped and control is passed to the statement that follows the loop in the program.
2. The set of statements inside the loop are executed if the condition returns true, after which the control loop iterates once again.

As long as the condition provided in the while loop is true, these two stages are repeated.

Python example of a while loop

Here is a while loop illustration. This example shows how to display a variable’s value in a loop while incrementing the value of the variable using the increment operator. This is a crucial step; without an increment or decrement, the while loop will run endlessly. We’ll cover this in more detail when we discuss infinite while loops.

num = 1
# loop will repeat itself as long as
# num < 10 remains true
while num < 10:
    #incrementing the value of num
    num = num + 3



Endless while loop

Example 1: Since the condition is always true, this will print the word “hello” indefinitely.

while True:

Example 2:

num = 1
while num<5:

Because we are not updating the value of num inside the loop, it will always be 1, which means the condition num 5 will always return true. As a result, this will display “1” indefinitely.

Python’s nested while loop

Nested while loops are those that contain one while loop inside of another. Let’s use an illustration to help you grasp this idea.

i = 1
j = 5
while i < 4:
    while j < 8:
        print(i, ",", j)
        j = j + 1
        i = i + 1


1 , 5
2 , 6
3 , 7

While loop with else block in Python

With a while loop, a “else” block is possible. The “else” section is not required. It doesn’t start running until the loop has finished.

num = 10
while num > 6:
   num = num-1
   print("loop is finished")


loop is finished

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button