Loops

LoopsΒΆ

Loops are a way of repeating commands over and over again.

A while loop is an indefinite loop. It runs indefinitely until a certain condition is met. Be careful with while loops. If the condition is never met, the while loop will try to run forever.

import numpy as np
i = 0
while i<5:
    i = i + 1
    print(i)
print('done with while loop')
1
2
3
4
5
done with while loop

A for loop is a definite loop. It iterates over a list, array or other variable types that are groups of values or other variables. It definitely stops when it gets to the end of the list.

name_list = ['Bob','Jane','Mary']
for name in name_list:
    print("Hello " + name)
print('done')         
Hello Bob
Hello Jane
Hello Mary
done

An example of looping through a sequence of numbers created with the np.arange() function.

import numpy as np
print(np.arange(5))
[0 1 2 3 4]
print(np.arange(2,5))
[2 3 4]
print(np.arange(2,5,0.5))
[2.  2.5 3.  3.5 4.  4.5]
for i in np.arange(5):
    print(i*2)
0
2
4
6
8

Exercise:

Write a for loop that prints out the cumulative sum of an array. For example, the cumulative sum of the array

[1,3,6,4,7]

would be:

[1,4,10,14,21]

algorithm - a process or set of rules followed in calculations or problem solving

x = [1,3,6,4,7]
cumsum = 0
for val in x:
    cumsum = cumsum + val
    print(cumsum)
print('done')
1
4
10
14
21
done
x_a = [1,3,6,4,7]
cumsum_a = 0
cumsum_array = []
for val in x_a:
    cumsum_a = cumsum_a + val
    cumsum_array = np.append(cumsum_array,cumsum_a)
    
print(cumsum_array)
[ 1.  4. 10. 14. 21.]