📓 About This Tutorial

This webpage is a static view of an interactive Jupyter Notebook tutorial. To get the full interactive experience where you can run Python code, modify examples and complete exercises, click the "Open in Colab" button. This will access the Google Colab notebook from a GitHub repository github.com/dchappell2/Computational-Physics and open it in Google Colab. You will need a Google account if you want to open it in Colab.

Note: You can download a pdf of the lecture slides for this chapter here: Chapter 5 slides

Chapter 5 - Loops

Goals:

5.0 Loops execute commands once for each value in a collection

5.1 A for loop is made up of a collection, a loop variable, and a body

for number in [2,3,5]:      # for loop over the collection [2,3,5]
    print(number)           # body of the for loop

5.2 The first line of a for loop must end with a colon, and the body must be indented

5.3 Loop variables can be called anything

Loop variables:

While the following is a valid for loop, the loop variable "kitten" probably doesn't add to our understanding of what the loop is for, unless the the collection [4,5,6] represents a kitten ID #. 🐱

for kitten in [4, 5, 6]:
    print(kitten)

✅ Skill Check 1

Write a for loop that prints each element of the following list, one item at a time: [2, 8, 18, 32, 50].

5.4 The body of a loop can contain many statements

🔆 Example: for loop over prime numbers

primes = [2, 3, 5, 7, 11]      # define a list of prime numbers
print(" prime  square   cube") # print a header labeling each data column
for p in primes:               # for loop, p will loop over elements of primes
    squared = p**2             # calculate square of p
    cubed   = p**3             # calculate cube of p
    print(f"    {p:2d}     {squared:3d}   {cubed:4d}")  # formatted print

5.5 Iterate over a list of non-numeric items

for loops can iterate over lists of non-numeric items in addition to numbers. In the following example, we use a for loop to iterate over a list of words. We use a formatted print statement to center-justify them.

word_list = ['top','quark','gravity','radiation', 'electromagnetic','pion']

for word in word_list:
    print(f"              {word:^15}")

✅ Skill Check 2

Create a for loop that iterates over the elements of the following list. Use a print statement inside the loop to print each list element.

my_list = ['I', 'am', 'Learning', 'Python']

5.6 use range() to iterate over a sequence of numbers

for n in range(3,8):
    print("n =",n)
for n in range(5):
    print("n =",n)
for n in range(0,10,2):
    print("n =",n)

🔆 Example: counting down

You can count backwards by using a negative step and letting the stop value be larger than the start value

for count in range(10,0,-1):
    print(count)

✅ Skill Check 3

```

for t in range(5):

x = 2*t**2

v = 2*t

print(f"t = {t} x = {x:2.0f} v = {v}")

```

✅ Skill Check 4

Write a for loop to count by fives starting from 5 and ending at 50. Your program should print out each value.

5.7 Use enumerate() to loop over values and the list index

primes = [2, 3, 5, 7, 11]                # define a list of prime numbers
i = 0                                    # initialized a counter to track the index
for p in primes:                         # loop over elements in primes
    print(f"index = {i}   prime = {p}")  # print index and value
    i = i + 1                            # increment the counter
primes = [2, 3, 5, 7, 11]               # define a list of prime numbers
for i,p in enumerate(primes):           # for loop, i = array imdex
    print(f"index = {i}  prime ={p}")   # print index and value

🔆 Example

Here's an example where knowing the list index could be helpful:

A = [2,5,8,3.14,'a','b']       # define list containing multiple data types

int_type = []                  # int_type will be a list containing indexes of
                               # intergers in the array. Initialize to empty list

for i,a in enumerate(A):       # loop over elements in list A
    if type(a) is int:         # check to see if the element is an integer
        int_type.append(i)     # if it is, add the index to our list
print("list of indices containging integer data:  ",int_type)

✅ Skill Check 5

Use the enumerate() command to iterate over the following list of items. Print the index and the array element.

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

5.8 Use zip() to loop over multiple lists

🔆 Example

mass = [0.1, 0.5, 0.9, 2.3]     # masses
vel  = [2.3, 1.2, 3.6, 5.5]     # velocity

KE = []                         # set kinetic energy list to empty list
for m,v in zip(mass, vel):      # loop over both mass and velocity lists
    KE.append(0.5*m*v**2)       # calculate and add KE to KE list

print("KE = ",KE)               # print KE

✅ Skill Check 6

twos   = [2,4, 6, 8,10]
threes = [3,6, 9,12,15]
fours  = [4,8,12,16,20]

5.9 The accumulator pattern sums or combines elements in a collection of numbers

Coding patterns are commonly used blocks of code that serve a particular function. The first coding pattern we will explore is called the Accumulator Pattern. It works as follows:

🔆 Example: Summing integers

The following example used the Accumulator Pattern to sum the integers from 1 to 10.

N = 10                    # N = upper limit of sum

total = 0                 # total = accumulator = sum of integers
for i in range(1,N+1):    # loop over integers 1 to N
    total = total + i     # add i to the running total

print("sum of integers from 1 to",N,"is",total)

🔆 Example: Extending a list

Another example of the accumulator pattern is "accumulating" items in a list.

my_list = [1]                      # initialize the list with 1

for n in range(10):                # for loop will calculate the next 10 items
    my_list.append(my_list[-1]*2)  # next item = previous item * 2

print(my_list)

✅ Skill Check 7

✅ Skill Check 8

✅ Skill Check 9

Write some code to produce the first 15 terms of the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8...

5.10 Nested loops

Here's the code:

print("  inner loop")

for b in [1, 2, 3]:
    print(f"     b = {b}")
print("inner loop done")

Here's the code:

print("outer loop    inner loop")  # header info before loops start

for a in [10, 20, 30]:             # outer loop, a = loop variable

    for b in [1, 2, 3]:            # inner loop, b = loop variable
        print(f"  a = {a}        b = {b}")    # only this statement is performed inside both loops
    print("inner loop done")       # display message after inner loop finishes

print("outer loop done")           # display message after outer loop finishes

✅ Skill Check 10

Trace the following code by hand (i.e. don't run it). Create a text box and write down what the code will output. If you like, you can copy the code in to a Code Cell to see if your prediction was correct.

```

for x in [1,10,100]:

s = x

for y in [0,1,2]:

s = s + y

print(x,y,s)

```

🔆 Example

The following program prints the numbers 1 to 100 in 10 columns using nested loops

for row in range(0,100,10):          # loop over rows
    for col in range(1,11):          # loop over columns
        product = row + col          # calculate the sum of the row and col variables
        print(f"{product:3d}  ",end="")   # print result suppressing line feed (don't start new line)
    print()                               # start a new line after previous row is done printing

✅ Skill Check 11

Create a multiplication table so that the table entry equals the product of the row number and the column number.

✅ Skill Check 12

5.11 while loops

🔆 Example

Here's a simple example to print all powers of 2 less than 100

p = 1             # initialize power
while p < 100:    # loop while power is less than 100
    print(p)      # display current value
    p = p * 2     # multiply power by 2

🔆 Example: Rolling dice

This example simulates rolling a 6-sided die. We count how many rolls it takes to get a predetermined roll (in this case a 6).

Run the program to see what it produces

import random           # import random library to use random number generator

target_roll = 6         # roll that you want to get
count = 0               # counter variable to count number of rolls
roll = -1               # initialize roll to any value other than the target

while roll != target_roll:         # loop while desired roll hasn't
    roll = random.randint(1,6)     # use random number generator to draw number between 1 and 6
    count = count + 1              # increase counter tracking number of rolls
    print("roll = ",roll)          # display current roll

# print message giving total number of rolls
print("Number of rolls to get",target_roll,"=",count)

✅ Skill Check 13

Modify the Rolling Dice program in the following way:

Key Points