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
Goals:
while loop runs continuously until some condition is metfor loop is made up of a collection, a loop variable, and a body[2, 3, 5] is what the loop is being run on. In this example, the collection is a Python list, but other objects can also serve as the collection.print(number), specifies what to do for each value in the collectionnumber, is what changes on each iteration of the loopfor number in [2,3,5]: # for loop over the collection [2,3,5]
print(number) # body of the for loop
number takes the value 2 (the first element of the collection.number takes the value 3 (second element of the collection) and so on.for loop must end with a colon, and the body must be indented{ } in C, or end in Matlab)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)
Write a for loop that prints each element of the following list, one item at a time: [2, 8, 18, 32, 50].
p that will loop over a list of prime numbers. The p reminds us the loop variable is a prime.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
{squared:3d} formatting tells python to reserve 3 spaces for digits in the squared numbers and {cubed:4d} reserves 4 spaces for cubes.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}")
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']
range() to iterate over a sequence of numbersrange(start,stop) function produces a sequence of integers from start to stop-1range() does not produce a Python list (which can take up lots of computer memory for long lists), rather, it generates the numbers on demand, one at a time.for n in range(3,8):
print("n =",n)
range(N) which generates the numbers: 0, 1, 2, ...N-1for n in range(5):
print("n =",n)
range(start,stop,step). For example, if step = 2, the for loop would begin counting by 2s from start.for n in range(0,10,2):
print("n =",n)
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)
```
for t in range(5):
x = 2*t**2
v = 2*t
print(f"t = {t} x = {x:2.0f} v = {v}")
```
Write a for loop to count by fives starting from 5 and ending at 50. Your program should print out each value.
enumerate() to loop over values and the list indexfor loop, only the values corresponding to each element in a list are accessible. The index isn't.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
enumerate() function, which returns two values: the index and the value for each element of the arrayenumerate() by using a commaprimes = [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
Here's an example where knowing the list index could be helpful:
if statement, which will be discussed in Chapter 6, so don't worry if if this part is confusing. We'll cover it soon.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)
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']
zip() function returns the elements for multiple listszip() function to loop over both the mass and velocity in a single loopmass = [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
zip() function to loop over all three lists. Hint: the zip() function can handle any number of lists.twos = [2,4, 6, 8,10]
threes = [3,6, 9,12,15]
fours = [4,8,12,16,20]
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:
The following example used the Accumulator Pattern to sum the integers from 1 to 10.
total to zero.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)
Another example of the accumulator pattern is "accumulating" items in a list.
my_list[-1] is the last item in the list, so 2*my_list[-1] multiplies the last element by 2.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)
x where $x! = 1\cdot 2\cdot 3 \cdots (x-1)\cdot x$NWrite some code to produce the first 15 terms of the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8...
[0,1]b and it will loop over the collection [1, 2, 3].b on each iteration of the loopHere's the code:
print(" inner loop")
for b in [1, 2, 3]:
print(f" b = {b}")
print("inner loop done")
a that will loop over the collection [10, 20, 30]a and bHere'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
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)
```
The following program prints the numbers 1 to 100 in 10 columns using nested loops
end="" option in the print statement. We then print a new line using print() after the inner loop is done.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
Create a multiplication table so that the table entry equals the product of the row number and the column number.
N = 1, 2, 3, 5, 10, 100.while loopswhile loop iterates while some condition remains true.while, specifices a condition to keep looping and ends with a colon :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
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).
random library to generate random numbersrandom.randint(a,b) generates a new random integer each time the command is called. The integer is drawn from a uniform distribution between a and b. We will use random.randint(1,6) to generate numbers between 1 and 6 inclusive.target_roll to be the value we want to roll (in our case 6)count is a counter to count how many rolls it takes to get our targetroll is the result of our random number generator used to simulate the dice roll.while loop keeps iterating as long as the dice roll is not equal to the target.random.randint(1,6) to simulate our dice rolltarget_roll, the condition roll != target_roll will be False and teh while loop will stop.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)
Modify the Rolling Dice program in the following way:
while loops keep looping as long as a specified condition is true