Home » Learn Python » Loops » While Loops

While Loops

Most often the kind of loop we need is a for loop. This iterates a specified number of times.

However, sometimes we don’t know in advance how many times the loop should iterate. In this case we use a while loop instead.

value = 0

while value < 5:
    print("Hello", value)
    value += 1
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4

The while loop must be supplied with a condition (an expression that evaluates to True or False). It will execute repeatedly as long as the condition remains True.

In this case the loop terminates when value is no longer less than 5.

The expression value += 1 adds one to the value variable every time we go around the loop. It is identical to value = value + 1

Note that, unlike some languages, Python does not have a ++ operator. In C, value++ would accomplish the same thing.

Leave a Reply

Blog at WordPress.com.