Python While Loops

Python While Loops with Example Code Snippet

Loops are an essential programming construct that allows us to execute a block of code multiple times. There are two types of loops in Python – for loop and while loop. While loops are used when we want to execute a block of code repeatedly until a certain condition is met.

In this blog, we will explore Python while loops in detail and provide an example code snippet.

Syntax of Python While Loop

The syntax of the while loop in Python is as follows:

while condition:
    # code to be executed

The while loop begins with the keyword while followed by a condition that is tested at the beginning of each iteration. If the condition is true, the code block is executed, and the loop continues. When the condition becomes false, the loop ends, and the program continues with the next statement after the loop.

Example Code Snippet

Let’s take an example to understand how while loops work in Python. Suppose we want to print the first 10 natural numbers using a while loop.

# Program to print the first 10 natural numbers using while loop
i = 1
while i <= 10:
    print(i)
    i = i + 1

In the above code snippet, we first initialize the variable i to 1. Then we use the while loop to print the value of i and increment it by 1 until it reaches 10. Once i becomes greater than 10, the loop terminates, and the program continues with the next statement after the loop.

Output:

1
2
3
4
5
6
7
8
9
10

Nested While Loops

We can also use nested while loops to perform more complex operations. A nested while loop is a loop within another loop. Let’s take an example of printing a pattern using nested while loops.

# Program to print a pattern using nested while loops
i = 1
while i <= 5:
    j = 1
    while j <= i:
        print("*", end="")
        j = j + 1
    print()
    i = i + 1

In the above code snippet, we use nested while loops to print a pattern of asterisks. The outer while loop controls the number of rows, and the inner while loop controls the number of asterisks to be printed in each row.

Output:

*
**
***
****
*****

Conclusion

In this blog, we have explored Python while loops and provided an example code snippet. While loops are useful when we want to execute a block of code repeatedly until a certain condition is met. Nested while loops can be used to perform more complex operations. We hope this blog has been helpful in understanding while loops in Python.