03 - Basic Loop#

We love loops because they go round and round. Seriously, loops help us complete repetitive tasks.

For Loop#

Sum all integers between 1 and 100

mysum = 0
for i in range(100):
    #mysum = mysum + i
    mysum += i
print(mysum)
4950

Is that correct?

Using Arrays#

import numpy as np
#first make empty array
numbers = []
for i in range(0,100):
    numbers.append(i)
print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
summation = 0
for number in numbers:
    summation += number #this is the same as summation = summation + number
print(summation)
4950
sum(numbers)
4950
np.array(numbers).std()
28.86607004772212
np.arange(0,101,1).std()
29.154759474226502

While Loop#

Sum integers until the index is 100

i = 0; mysum =0
while i <= 100: #any condition could be used; loop is executed as long as the condition is true
    mysum += i
    i += 1
print(mysum)
5050

Nested Loops#

There are times that you’ll have a loop inside another loop. For example, to cycle through a two-dimensional array.

alist = []
for i in range(5):
    btemp = []
    for j in range(4): #also could just write while center:
        btemp.append(j*i)
    alist.append(btemp)
print(alist)
[[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6], [0, 3, 6, 9], [0, 4, 8, 12]]

Inline Loop#

An inline loop is shorthand for a loop. It is written in a single line using a list notation.

listofnumbers = [each for each in range(0,100)]
np.sum(listofnumbers)
4950

Infinite Loop#

#This would yield an infinite loop, why?
#i = 0; mysum =0
#while i <= 100: #any condition could be used; loop is executed as long as the condition is true
#    mysum += i

#print(mysum)

You don’t want this to happen. It usually will crash your computer.