How to Use a While Loop in Python

In Python, Loops are used for repeating a block of code multiple times. One of the types of loops in Python is the While Loop. It continuously executes a block of statements as long as the given condition is true. In this tutorial, we will discuss how to use the While Loop in Python.

Step 1: While Loop Syntax

The syntax for a While Loop in Python is:

Here, statement(s) may be a single statement or a block of statements with indented same space. The condition may be any expression. True always is the result if the condition is true, the loop continues. If the condition becomes false, program control passes to the line immediately following the loop.

Step 2: Simple While Loop Example

Here is a simple example of using a While Loop in Python:

In this script, the variable i is initialized at 1. The while loop runs as long as i is not greater than 5. Inside the loop, we print the value of i and then increment it by 1 each time the loop runs.

Step 3: Flow Control in a While Loop

In Python, we can control the execution flow of the while loop using break, continue and pass statements. Read more about them on the official Python documentation page.

Full Code


Learning how to use while loops in Python opens up new possibilities for automation and repetition in your programming projects. These examples show the basic use of while loops, but you can use them in much more complex ways in your own scripts to perform a variety of tasks. Continue practicing to get the hang of them, and explore the official Python documentation to learn more about different methods and techniques.