Loops#

Author: Mike Wood

Learning objectives: By the end of this notebook, you should be able to:

  1. Utilize a for loop to iterate through a series of objects

  2. Implement a while loop to continue excuting code as long as a condition is met

For Loops#

A for loop is a convienent piece of code that allows us to run a particular code block on a series of objects. Python provides several ways that for loops can be implemented. For example, a for loop can be used to iterate over a list:

# print the letters from the list
letters = ['A','B','C','D','E']
for letter in letters:
    print(letter)
A
B
C
D
E

A for loop can also iterate over a range of numbers

# print all numbers up to 10
for number in range(10):
    print(number)
0
1
2
3
4
5
6
7
8
9

In addition, for loops can be combined with if statements to achieve the power of both types of code blocks. To implement an if statement inside a for loop, provide another layer of indentation:

# print all of the even numbers up to 10
for number in range(10):
    if number%2 == 0:
        print(number)
0
2
4
6
8

πŸ€” Mini-Exercise#

Goal: Make a list all prime numbers between 2 and 100. A prime number is one which is not divisible by any other number. For example, 5 is prime because all numbers lower than 5 (not including 1) have a non-zero remainder:

print(5%4)
print(5%3)
print(5%2)
1
2
1

On the other hand, 6 is not prime because it has a zero-divisor:

print(6%5)
print(6%4)
print(6%3)
print(6%2)
1
2
0
0

For this exercise, use for loops and if statements to test whether each number between 2 and 100 is prime. If it’s prime, then add it to a list called prime_numbers. At the end of your code, print out the list.

πŸ’‘ Solution#

# write code to make a list of prime numbers between 2 and 100
prime_numbers = []

# loop through all the numbers
for number in range(2,101):
    
    # assume the number is prime until we have evidence otherwise
    number_is_prime = True
    
    # check each divisor up to the number
    for divisor in range(2,number):
        
        # if the number is divisble by the divisor,
        # then the number is not prime
        if number%divisor==0:
            number_is_prime = False
    
    # if the number is prime, then add it to the list
    if number_is_prime:
        prime_numbers.append(number)

#print out the numbers
print(prime_numbers)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

While Loops#

While loops in Python are the same as in other languages – the loop will continue to run until a particular condition is met. The condition must be a Boolean expression that returns either True or False.

Boolean Operators#

The following table lists a common set of Boolean operators that yeild True or False conditions.

operator

symbol

less than

<

less than or equal

<=

is equal

==

greater than or equal

>=

greater than

>

not equal

!=

# write a while loop to print all numbers between 5 and 20 (inclusive)
number = 5
while number<=20:
    print(number)
    number += 1
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Combining Boolean Operators#

In Python, combining boolean operators is simple – just use the key words or or and!

# write a loop to print numbers between 5 and 20, but don't print more than 5 values
number = 5
count = 0
while number<=20 and count<5:
    print(number)
    number += 1
    count += 1
5
6
7
8
9

❗ Infinite Loops#

When using a while loop, it is incredibly easy to write an infinite loop. It’s always a good idea to know how to escape an infinite loop. When running from the command line, you can use the standard CTRL-C to stop code that is running. In a Jupyter Notebook, use the Stop button.

# this is an infinite loop
# uncomment to test out this code
# run it and practice killing it so you known how to stop an infinite loop
# i=0
# j=0
# while i==0:
#     j+=1