How To Write A While Loop In Python

While loops are an essential control flow structure in Python programming that allows you to execute a block of code repeatedly until a specific condition is met. In this tutorial, we will walk you through the process of writing a while loop in Python for different use cases.

Step 1: Understand the Basic Structure of a While Loop

A while loop in Python has the following syntax:

The condition is an expression that returns a boolean value (True or False). If the condition evaluates to True, the code inside the loop is executed. If the condition is False, the loop is skipped, and the program continues with the remaining code outside the loop.

Step 2: Create a Simple While Loop

Let’s create a simple while loop to print numbers from 1 to 5. In this example, we will use a loop variable i and set its initial value to 1. Our condition checks whether i is less than or equal to 5. Inside the loop, we print the value of i and then increment its value by 1.

Output:

1
2
3
4
5

Step 3: Use the Break Statement

The break statement can be used to exit the loop early, before the loop condition becomes False. This is useful when you have some code inside the loop that might change the loop condition, and you want to exit the loop based on a specific situation.

For example, let’s say we want to print numbers from 1 to 5, but we want to stop as soon as the number 3 is encountered:

Output:

1
2

Step 4: Use the Continue Statement

The continue statement can be used to skip the current iteration of the loop and continue with the next iteration. In this example, let’s print all numbers from 1 to 5, but skip the number 3:

Output:

1
2
4
5

Step 5: Use the Else Clause

The else clause in a while loop is executed when the loop condition becomes False. This can be helpful to execute a block of code only once after the loop completes all its iterations. For example, let’s print numbers from 1 to 5 and then print “Loop completed” after the loop finishes:

Output:

1
2
3
4
5
Loop completed

Conclusion

In this tutorial, we covered the basics of while loops in Python, along with important concepts like the break and continue statements, and the else clause. With these concepts, you are now equipped to write efficient and flexible while loops for various scenarios in your Python programs.