Python while Loop
The while loops are used when you have a block of code which you want to repeat ** until a defined condition is no longer met**.
Syntax
The while loops repeat a block of code ** until a defined condition is no longer met**.
If the condition is initially false, the loop body will not be executed at all.
The syntax of the while loop is as follows
while <condition>:
<statement>
<statement>
...
where:
<condition>
is any expression that evaluates to a Boolean- All
<statements>
are executed once for each iteration.
For example:
i = 0
while i < 4:
print(i)
i = i + 1
Output
0
1
2
3
while loop with else
A while loop can also have an optional else
block.
The else
statements are executed only if the while loop ends normally (i.e., if the condition becomes false).
The syntax is the same as a classic while loop, but with the addition of the else branch:
while <condition>:
<statement>
<statement>
...
else:
<else-statement>
...
The break keyword can be used to break a while loop. In such cases, the else part is ignored.
Nested while Loops
As with other flow-control structures, such as if and for loops, while loops can also be nested.
For example:
i = 1
while i < 4:
j = 1
while j < 4:
print(f"{i} + {j} = {i+j}")
j = j + 1
i = i + 1
Output:
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
2 + 1 = 3
2 + 2 = 4
2 + 3 = 5
3 + 1 = 4
3 + 2 = 5
3 + 3 = 6
Manipulate while loop execution
break statement in while loop
Python break statement is used to exit the loop immediately. It simply jumps out of the while loop and the program continues to execute the code after the loop.
For example, break the loop at yellow
colors = ['red', 'green', 'yellow', 'blue']
i = 0
while i < len(colors):
i = i + 1
if colors[i-1] == 'yellow':
break
print(colors[i-1])
Output
red
green
continue statement in while loop
Python continue instruction skips the current iteration of a loop and continues with the next iteration.
For example, continue the loop at yellow
colors = ['red', 'green', 'yellow', 'blue']
i = 0
while i < len(colors):
i = i + 1
if colors[i-1] == 'yellow':
continue
print(colors[i-1])
Output
red
green
blue
pass statement in while loop
Python pass statement is a null statement: nothing happens when it is executed.
For example, pass the loop at yellow
colors = ['red', 'green', 'yellow', 'blue']
i = 0
while i < len(colors):
i = i + 1
if colors[i-1] == 'yellow':
pass
print(colors[i-1])
Output
red
green
yellow
blue
Infinite Loops (while true)
The while loop is repeated as long as the condition remains True.
If the while condition does not become false, the loop will execute forever. This situation creates an infinite loop (also called endless loop).
To terminate an infinite loop, it is necessary to use a break
statement
For example, read a number from the user until a number greater than 10 is entered:
while True:
number = float(input('Enter a number: '))
if number > 10: break
print(f'The number is {number}')
Output
Enter a number: 3
The number is 3.0
Enter a number: 10
The number is 10.0
Enter a number: 12
Examples
Let's look at some examples of frequent situations when programming in python
Iterating a String
Each string can be iterated character by character, using an auxiliary variable to hold the index and using the [ ]
operator.
For example:
string = "Tutorial"
i = 0
while i < len(string):
print(string[i])
i = i + 1
Output
T
u
t
o
r
i
a
l
Iterating a List
Lists can be iterated with while loop, using an auxiliary variable to hold the index and using the [ ]
operator.
For example:
collection = ['a string', 123, 'a', 1.2]
i = 0
while i < len(collection):
print(collection[i])
i = i + 1
Output
a string
123
a
1.2
Loop over Lists of lists
Using nested while loops, lists of lists can be iterated, using auxiliary variables to hold the index and the [ ]
operator.
For example:
list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
i = 0
while i < len(list_of_lists):
# list_of_lists[i] returns the i-th nested-list
j = 0
while j < len(list_of_lists[i]):
# list_of_lists[i][j] returns element j-th of the i-th nested-list of list_of_lists
print(list_of_lists[i][j])
j = j + 1
i = i + 1
Output
1
2
3
4
5
6
7
8
9