Introduction to while-loops
In this lesson, you will get to know while-loops, the second type of loop in Python. While-loops continuously execute a block of code as long as a certain condition is true.
Consider the following list of tasks
tasks = ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5']
Imagine we want to perform each task until the list is empty.
This means we need to remove an item from the list each time we perform a task.
Theoretically, we could do this using a for-loop. Intuitively, you might write the following:
tasks = ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5']
for task in tasks:
print('Performing task: ', task)
# remove task from tasks
tasks.remove(task)
But, using a for-loop in this scenario is not a good idea. The code won't work as expected.
You should never modify the sequence you are iterating over within a for-loop. This will have unexpected results.
Instead, you can use a while loop.
While loops in Python are used to repeatedly execute a block of code as long as a specified condition is true.
The syntax of a while loop is as follows:
while condition:
# Code block to be executed
Here's a simple example:
x = 0
while x < 5:
print(x)
x += 1
As long as x is less than 5, we print x and add 1.
This continues for five iterations until x reaches 5, and then the loop terminates.
Let's return to our example with the list of tasks.
Here's how you would do it using a while loop:
tasks = ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5']
while len(tasks) > 0:
# remaining tasks:
print(tasks)
# remove task from tasks
current_task = tasks.pop(0)
# perform current task
print(current_task)
As long as tasks has at least one element, the loop continues to run, removing the first task of the list in each iteration.
What will be the output?
text = ''
while len(text) < 4:
text += 'X'
print(text)
What will be the output?
text = ''
while len(text) < 4:
text += 'X'
print(text)
What will be the output?
count = 3
while count > 0:
print(count)
count -= 1
print('Liftoff')
When working with while loops, you need to be careful not to accidently create an infinite loop.
Here we have such an infinite loop. Can you see why?
while 2 > 1:
print(True)
The loop will continue running indefinitely because the condition 2 > 1
is always true.
You can use both break
and continue
in a while loop:
num = 0
while num < 10:
num += 1
if num == 5:
print('Breaking loop')
break
if num % 2 == 0:
print('Skipping even number')
continue
print(num)
What will be the output?
num = 1
while num > 0:
num += 1
print(num)
if num > 3:
break