3.2. Looping for Repetitive Tasks#

There are many times when you’ll want to do a repetative task (e.g., perform a calculation 100 or 1000 times) and using programming is a way to make that task more effecient. Iteration is a key component to any programming language due to the need to process data in a time effecient manner and Python offeres two different methods for looping (iterating) over a series of values: for loops and while loops.

For Loops#

In Python, the for loop is the most extensible method for iterating over an object. You are not relegated to just looping over a series of integer values, but can loop over a mixed list or other iterable object (e.g., dictionary keys). The construct of a for loop is:

for var in iter_obj:
    [code block]

Again, the syntatical structure of Python using the color at the end of the for loop line and everything that you want done with each cycle of the loop needs to be indented.

Common Iterable Objects:

  • range() function

  • List

  • Tuple

  • Dictionary Keys

Note

A common way to create a quick for loop over a set of sequential values is to set up a range of values using the built-in range function. One note is that the range function is inclusive of the first value and exclusive of the second.

range(0, 10) -> [0, 1, 2, 3, 4 ,5 , 6, 7, 8, 9]

So how does the loop work?

For each element in the iterable object (e.g., [0, 1, 2, 3, 4]) the variable var, which is defined as the looping variable, assumes the values in sequence. So initially, var will have the value of 0, it holds that while working through all of the code within the loop, then once you hit the end of the loop you go back to the beginning and var takes on the next value. This continues until all values in the iterable object are exhausted.

Let’s explore an example to see how it works…

for var in [0, 1, 2, 3, 4]:
    print(var)
    if var < 1:
        print(f'{var} is less than 1')
    else:
        print(f'{var} is greater than or equal to 1')
print('Out of loop')

Output:

0
0 is less than 1
1
1 is greater than or equal to 1
2
2 is greater than or equal to 1
3
3 is greater than or equal to 1
4
4 is greater than or equal to 1
Out of loop
from datetime import datetime, timedelta
# For loop example 1

for i in range(0, 10):
    print(f'The value of i is {i}')

print()
print('I am now out of the loop!')
The value of i is 0
The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5
The value of i is 6
The value of i is 7
The value of i is 8
The value of i is 9

I am now out of the loop!
# For loop example 2

for time in [1215, 1245, 1315, 1345, 1415]:
    print(time)
1215
1245
1315
1345
1415
# For loop example 3

for var in ['Kevin', 1859, 2.5, 'Keaton']:
    print(f'The varible is {var}')
The varible is Kevin
The varible is 1859
The varible is 2.5
The varible is Keaton

While Loops#

There may be times you want to continue looping until a condition is met. Here we have a simple example that starts a loop at zero and goes to 11. Basically we are combining looping with testing the truth value of a statement. As long as the statement remains True, the loop will continue going. This is why it is important to ensure that the looping variable changes in some manner that can be eventually evaluated as False, so that you don’t create an infinite loop!

# While loop example

# Set the starting loop value
inc = 0

# Check the value compaired to max value
while inc < 12:
    # Print current increment value
    print(inc)
    # Update value
    inc += 1
0
1
2
3
4
5
6
7
8
9
10
11