Loops

Sometimes, it is helpful to execute code multiple times. Python gives us a language construct called a loop that will execute some code multiple times.

Python supports two types of loops:

Loop Type Syntax Usage
for for i in range(start,end,step): Looping for some discrete number of times.
while while condition: Loop for an indefinite number of times.

The number of times a loop executes is called the number of times the loop iterates.

For Loop Examples

The for loop above uses a range iteration. The range function can take 1, 2, or 3 parameters (start, end, and/or step).

start = 1
end = 5
for i in range(start, end):
   print(i)

The code above prints the following:

1
2
3
4

The range function will produce numbers within the range: [start..end). In other words, it produces numbers from start up to but not including end.

NOTE: The range function only produces an increasing range. If start is >= end, the range function will produce nothing.

You are permitted to produce an ending point, at which start will start at 0. For example:

for i in range(5):
   print(i)

The code above prints the following:

0
1
2
3
4

You can also specify the amount you want each step to increase. Right now, the numbers increase by one. However, we can grow the number by any arbitrary amount.

# range(start, end, step)
#   start = 10
#   end   = 20
#   step  = 5
for i in range(10, 20, 5):
   print(i)

The function call range(10, 20, 5) will start producing numbers at 10 and then increase the value by 5 up to but not including where the number is >= 20. Therefore, the code above produces the following:

10
15

Notice that 20 is not printed in this range. This is because range excludes the end.

While Loops

While loops will indefinitely loop until the condition is False.

a = 0
while a < 5:
    print(a)
    a = a + 1

The code above will print the following:

0
1
2
3
4

Notice that we converted the previous for loop into a while loop. Essentially, as long as the condition a < 5 is True, the loop will continue to execute the code indented below it.


Stephen Marz (2019)