While Loop in Python with Examples

The while loop in Python executes a block of code repeatedly as long as a given condition evaluates to True. Unlike the for loop, which requires you to specify the number of iterations at the beginning, the while loop continues to execute as long as it needs to in order to satisfy the condition. I highly recommend you get the “Python Crash Course Book” to learn Python.

Example 1: While Loop in Python

This is a simple while loop. It will print the numbers until the number is less than 8.

n = 1
while n < 8:
    print(n)
    n += 1

Output:

1
2
3
4
5
6
7

Example 2: While Loop with Break Statement

Sometimes we want to break our while loop at some specific condition then we use a break statement for this purpose. In this example, I will use the while loop that will print the numbers until the number is less than 8 but if the number is equal to 4 then the while loop will break.

n = 1
while n < 8:
    print(n)
    if n == 4:
        break
    n += 1

Output:

1
2
3
4

Example 3:

This example is the same as above but only one thing is different. It will not print 4 because the print command is below the break statement in this example.

n = 1
while n < 8:
    if n == 4:
        break
    print(n)
    n += 1
1
2
3

Example 4: While Loop with Continue Statement

The continue statement is used in the while loop if we want to skip a value. In the following example, the continue statement is used to skip 4. It will go to the next step.

n = 0
while n < 8:
    n += 1
    if n == 4:
        continue
    print(n)
1
2
3
5
6
7
8

Leave a Comment

Your email address will not be published.