Loops

Lesson Progress
0% Complete

While Loop

A while loop will run until a boolean test returns false.

while condition:
    indented body lines

The loop checks the given condition. If False, the program continues beyond the loop. If True, the code in the loop is executed. Once the code inside the loop is finished, the condition is checked again and the cycle repeats if True.

For Loop

A for loop runs a piece of code once per item in a collection.

>>> for num in [2, 4, 6, 8]:
...     print(num)
2
4
6
8

In the above example, a for loop iterates over list [2, 4, 6, 8]. In each iteration, the current list item is assigned to the keyword num and is used to print the current number.

The range function forms a common code pattern with for loops.

for i in range(10):
    print(i)
for i in range(len(s)):
    print(s[i])

In the first example above, the loop will print 10 numbers from 0-9 inclusive based off the iterable object returned by range(). In the second example, range(len(s)) creates an iterable corresponding to each of a string’s indices. The loop then prints out each character on a new line.

Loop flow

The break and continue directives provide powerful ways to control the flow and logic of loops.

Break

The break directive will exit a loop without executing any additional code and without re-starting the loop.

Continue

The continue directive will skip to the next iteration of a loop without executing any additional code for that iteration.