# IMPORT DATA FILES USED BY THIS NOTEBOOK
import os, requests
file_links = [("data/ChemicalSymbols.csv", "https://ndcbe.github.io/cbe-xx258/data/ChemicalSymbols.csv")]
# This cell has been added by nbpages. Run this cell to download data files required for this notebook.
for filepath, fileurl in file_links:
stem, filename = os.path.split(filepath)
if stem:
if not os.path.exists(stem):
os.mkdir(stem)
if not os.path.isfile(filepath):
with open(filepath, 'wb') as f:
response = requests.get(fileurl)
f.write(response.content)
Reference: Chapters 2 and 5 of Computational Nuclear Engineering and Radiological Science Using Python, R. McClarren (2018)
After studying this notebook, completing the activities, and asking questions in class, you should be able to:
You can also do other fun stuff with for loops. For instance, you can have the control variable take on non-numeric things:
#silly hat code
hats = ["fedora","trilby","porkpie","tam o'shanter",
"Phrygian cap","Beefeaters' hat","sombrero"]
days = ["Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday","Sunday"]
count = 0
for today in hats:
print("It is",days[count],"and I will wear a",today)
count += 1
Notice what else we did here: we defined a list called days
that contained strings for the names of the days of the week. Inside our for
loop we had a numeric variable that kept track of what number the day of the week was (0 for Monday in this case). Then when we access days[count] it returns the string in position count.
We can go one step beyond and plan our wardrobe a month in advance using random numbers. The code below generates a random integer between 0 and 6:
import random
my_random_number = round(random.uniform(0,6))
print(my_random_number)
#silly hat code
import random
hats = ["fedora","trilby","porkpie","tam o'shanter",
"Phrygian cap","Beefeaters' hat","sombrero"]
days = ["Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday","Sunday"]
# loop over 30 days
# YOUR SOLUTION HERE
Lists are like vectors in MATLAB, except, as you can see above, we can store more than just numbers in them. We will talk about using a package numpy
to represent vectors and matrices next class session.
## Attempt 1
N = [1, 2, 3, 4, 5, 6, 7, 11]
for i in range(len(N)):
print(i+1)
# YOUR SOLUTION HERE
## Attempt 2
N = [1, 2, 3, 4, 5, 6, 7, 11]
for i in range(len(N)):
print(N[i])
# YOUR SOLUTION HERE
## Attempt 3
for i in range(0,10):
print(i)
# YOUR SOLUTION HERE
So far, we have used lists to store a sequence of numbers or more generally Python objects. Lists (and NumPy arrays - stay tuned) access elements by position and have an inherent ordering.
A dictionary is a set of key : value pairs. You can think of a dictionary as a fancy list that instead of accessing via the position, you access using a key.
#simple dictionary
days_of_week = {"M":"Monday", "T":"Tuesday",
"W":"Wednesday", "R":"Thursday",
"F":"Friday", "S":"Saturday",
"U":"Sunday"}
print("Key M gives", days_of_week["M"])
print("Key R gives", days_of_week["R"])
# YOUR SOLUTION HERE
Calling days_of_week.keys()
returns a special list of the keys of the dictionary.
print(days_of_week.keys())
We can also check if G
is a valid key for the dictionary.
print("G" in days_of_week.keys()) #is G a key in days_of_week?
Main idea: With dictionaries, we access elements using the key. In contrast, we access elements of strings, lists, and Numpy arrays using the position.
# YOUR SOLUTION HERE
Below is code that parses ChemicalSymbols.csv
and stores the data in dictionary.
import csv
element_dict = {} #create a blank dictionary
# this block will only execute if the file opens
with open('./data/ChemicalSymbols.csv') as csvfile:
chemreader = csv.reader(csvfile)
for row in chemreader: # have for loop that loops over each line
element_dict[row[0]] = row[1] # add a key:value pair
# Ask user to enter a chemical symbol
key = input("Enter a valid chemical symbol: ")
if key in element_dict:
print(key,"is",element_dict[key])
else:
print("Not a valid element")
We can also print out the dictionary.
print(element_dict)
element_dict
We can make dictionaries even more powerful if we make a dictionary of dictionaries.
Top Level. Day of the week.
Second Level. Data for each day.
#simple dictionary of dictionaries
days_of_week = {"M":{"name":"Monday","weekday":True,"weekend":False},
"T":{"name":"Tuesday","weekday":True,"weekend":False},
"W":{"name":"Wednesday","weekday":True,"weekend":False},
"R":{"name":"Thursday","weekday":True,"weekend":False},
"F":{"name":"Friday","weekday":True,"weekend":False},
"S":{"name":"Saturday","weekday":False,"weekend":True},
"U":{"name":"Sunday","weekday":False,"weekend":True}}
print("The days that are weekdays are")
for day in days_of_week: #for loop over dictionary, loops over keys
if days_of_week[day]["weekday"] == True:
print(days_of_week[day]["name"],"is a weekday.")
print("The days that are weekend days are")
for day in days_of_week: #for loop over dictionary, loops over keys
if days_of_week[day]["weekend"] == True:
print(days_of_week[day]["name"],"is a weekend, whoop.")
Notice that when you loop over a dictionary in a for loop, the loop variable will get each of the keys of the dictionary.
The dictionary has been modified to include the day name in Spanish.
#more complicated dictionary of dictionaries
days_of_week2 = {"M":{"name":"Monday","weekday":True,"Spanish":"Lunes"},
"T":{"name":"Tuesday","weekday":True,"Spanish":"Martes"},
"W":{"name":"Wednesday","weekday":True,"Spanish":"Miércoles"},
"R":{"name":"Thursday","weekday":True,"Spanish":"Jueves"},
"F":{"name":"Friday","weekday":True,"Spanish":"Viernes"},
"S":{"name":"Saturday","weekday":False,"Spanish":"Sábado"},
"U":{"name":"Sunday","weekday":False,"Spanish":"Domingo"}}
# YOUR SOLUTION HERE
Let's see some syntax for growing lists.
# create a list with nothing
students = []
# add a student
students.append("Joe Smith")
# add another student
students.append("Jane Doe")
print(students)
How to loop for the list? Let's review.
# Approach 1
for s in students:
print(s)
# Approach 2
for i in range(len(students)):
print(i,": ",students[i])
Can simply the syntax? It is really convienent to access the index with i
and the student with s
.
for i, s in enumerate(students):
print(i,": ",s)