Python While Loops are one of the most used methods in Python Programming. We use while loops in python to run any statements as long as the condition of while is true. The other loop method used in python is for loops. We have talked about Python For Loops in the related lesson.
Now, to learn Python While Loops better, let’s give some examples.
In the below example, we will asign a value, 0 to x variable. Then we will create while loop that controls the value of x if lower than 5. And As long as it is lower than 5, we will print the value of x.
The output of this python code will be:
You can also check Python If Else
In the below other example, we will use python while loop top rint the lenght of the strings in the string list. Here, we will control the index variable value to control all the items in the string list. Then, we will use lenght print as long as the while loop is true.
With another example, let’s print the even numbers is a given list. Here, we will use if statement with Python While Loop.
The ouput will be:
There are two important statements that can be used with while loops. These are :
Break statement is used to stop the execution of while loop.
Continue statement is used to jump over the step that the code in.
Let’s do two example to learn these statements and their usage with while loop in python.
In the below example, we will use break statement to stop the while loop when the variable reach a value, 5.
The output of this code will be:
In the below example, we will use continue statement not to print two numbers, 3 and 5.
The output will be:
In this Python While Loop lesson, we have learned how to use while loops in python. You can create your while loop examples to learn this one of the most important python statement better.