While Loops in Python

Loops are used when you need to repeat a block of code a certain number of times or apply the same logic over each item in a collection.

There are two types of loops: for and while.

In this article, I will focus on while loops.

To learn about for loops, check out this article on For Loops in Python.

Basic Syntax

The basic syntax of a while loop is as below.

while condition:
    statement

The loop will continue until the condition is True.

The square of a number is

The example below takes each value of number and calculates its squared value.

number = 1
while number <= 5:
    print(number, 'squared is', number**2)
    number = number + 1
#output:
#1 squared is 1
#2 squared is 4
#3 squared is 9
#4 squared is 16
#5 squared is 25

You can use any variable name, I chose number because it makes sense in the context, but a common generic choice would be simply i.

The loop will go on until number, which is initialized with 1, is less than or equal to 5.

Notice that after the print() command, the variable number is incremented by 1 to take the next value.

If you don’t do the incrementation you will have an infinite loop since number will never reach a value greater than 5. This is a very important detail!

else block

You can use the else block, similar to what is done in Conditionals in Python.

When the condition returns False, the else block will be called.

number = 1
while number <= 5:
    print(number, 'squared is', number**2)
    number = number + 1
else:
    print('No numbers left!')
#output:
#1 squared is 1
#2 squared is 4
#3 squared is 9
#4 squared is 16
#5 squared is 25
#No numbers left!

Notice the phrase ‘No numbers left!’ is printed after the loop ends, that is, after the condition number <= 5 evaluates to False.

How to break out of a while loop in Python?

Simply use the break keyword, and the loop will stop its execution.

number = 1
while number <= 5:
    print(number, 'squared is', number**2)
    number = number + 1
    if number == 4:
        break
#output:
#1 squared is 1
#2 squared is 4
#3 squared is 9

The loop runs normally and when number reaches 4, the if statement evaluates to True and the break command is called, finishing the loop before the squared value of the numbers 4 and 5 are calculated.

How to skip an item in a while loop?

The continue will do that for you.

I had to invert the order of the if statement and the print() to show how it works properly.

number = 0
while number < 5:
    number = number + 1
    if number == 4:
        continue
    print(number, 'squared is', number**2)

#output:
#1 squared is 1
#2 squared is 4
#3 squared is 9
#5 squared is 25

I always check if 4 is the current value of number, if it is, the square of 4 won’t be calculated and the continue will skip to the next iteration when the value of number is 5.