While Loops¶
A while
loop is similar to a for
loop in that it is a tool used to automate a repetive task. The core difference between while
and for
loops is as follows:
A
for
loop executes a predetermined number of times. Afor
loop that begins with"for i in range(a,b)"
will execute exactly once for each value of the counteri
that falls within the given range.A
while
loop executes as long as some supplied condition is true. Depending on the nature of this condition, we do not necessarily know ahead of time how many times the loop will execute.
The syntax for creating a while
loop is as follow:
while condition: code to be executed each iteration
The condition
in a while statement should be an expression that evaluates to a Boolean value. When Python encounters a while
loop, it will check to see if the condition evaluates to True
. If it does, then it will step into the loop and perform the first iteration. Each time the loop executes, Python returns to the start of the loop and checks the condition again. As long as the condition evaluates to True
, Python will continue executing iterations of the loop. If the condition ever evaluates to False
, then Python will stop executing the body of the loop, and will move on to the next lines of code.
The following cell illustrates a simple example of a while
loop. The cell prints out the squares of the first five positive integers.
n = 1
while n <= 5:
print(n**2)
n += 1
1
4
9
16
25
The task above could have been accomplished more succinctly using a for
loop:
for n in range(1,6):
print(n**2)
1
4
9
16
25