Python While Loop

python-while-loop-ipcisco-2

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.

 

x = 0
while x < 5:
  print(x)
  x += 1

 

The output of this python code will be:

 

0
1
2
3
4

 


You can also check Python If Else


 

python-while-loop-ipcisco-1

 

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.

 

greetings = ["merhaba", "hello", "bonjour", "hola"]
index = 0
while index < len(greetings):
    x = greetings[index]
    print(len(x))
    index += 1

 

7
5
7
4

 

python-while-loop-ipcisco-2

 

With another example, let’s print the even numbers is a given list. Here, we will use if statement with Python While Loop.

 

numbers = [10,15,24,36,47,55,62]
index = 0
x = 0
while index < len(numbers):
    x = numbers[index]
    if  x % 2 == 0:
               print(x)
    index += 1

 

The ouput will be:

 

10
24
36
62

 

python-while-loop-ipcisco-3

 

There are two important statements that can be used with while loops. These are :

 

  • Break
  • Continue

 

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.

 

x = 0
while x < 10:
  x += 1
  if x == 5:
    break
  print(x)

 

The output of this code will be:

 

1
2
3
4

 

 

 

In the below example, we will use continue statement not to print two numbers, 3 and 5.

 

x = 0
while x < 10:
  x += 1
  if x == 3:
    continue
  if x == 5:
    continue
  print(x)

 

The output will be:

 

1
2
4
6
7
8
9
10

 

python-while-continue-stetement-ipcisco

 

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.

 

Back to: Python Programming Course > Python Loops

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand