Lecture Notes - Lists, Dictionaries, Iteration
Lecture Notes August 30, 2022
list = [1, 2, 3, 4]
print("list", list, type(list), "length", len(list))
print('- list[3]', list[3], type(list[3]))
langs = ["Python", "JavaScript", "Java", "bash"]
print("langs", langs, type(langs))
print("- langs[0]", langs[0], type(langs[0]))
name = "Evan"
print("What is the value of variable name:", name)
Notes can be made this way.
InfoDb = []
# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
"FirstName": "Evan",
"LastName": "Aparri",
"DOB": "November 10, 2005",
"Residence": "San Diego",
"Email": "evanaparri@gmail.com",
"Owns_Cars": "none",
"Hobbies": ["sleeping"]
})
print(InfoDb)
# Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Sunny",
"LastName": "Naidu",
"DOB": "August 2",
"Residence": "Temecula",
"Email": "snaidu@powayusd.com",
"Owns_Cars": "4Runner",
"Hobbies": ["eating"]
})
print()
print()
# Print the data structure
print(InfoDb)
InfoDb = []
# InfoDB is a data structure with expected Keys and Values
# Append to List a Dictionary of key/values related to a person
InfoDb.append({
"FirstName": "John",
"LastName": "Mortensen",
"Gender": "Male",
"DOB": "October 21",
"Residence": "San Diego",
"Email": "jmortensen@powayusd.com",
"Fav_Color": "Unknown",
"Sleep_Schedule" : "Unknown",
"is_Teacher": True,
"Hobbies": ["Teaching", "Programming"],
"Games": [],
"Owns_Cars": ["2015-Fusion", "2011-Ranger", "2003-Excursion", "1997-F350", "1969-Cadillac"]
})
InfoDb.append({
"FirstName": "Evan",
"LastName": "Aparri",
"Gender": "Male",
"DOB": "November 10, 2005",
"Residence": "San Diego",
"Email": "evanaparri@gmail.com",
"Fav_Color": "Blue",
"Sleep_Schedule" : "2am",
"is_Teacher": False,
"Hobbies": ["Running", "Reading", "Eating Asian Food/ Food Connoisseur", "Sleeping", "Homework", "Programming"],
"Games": [],
"Owns_Cars": ["2001-Camry"]
})
InfoDb.append({
"FirstName": "Alex",
"LastName": "Lu",
"Gender": "Male",
"DOB": "November 29, 2006",
"Residence": "San Diego",
"Email": "maodou1258@gmail.com",
"Fav_Color": "White",
"Sleep_Schedule" : "1am",
"is_Teacher": False,
"Hobbies": ["Programming", "Tennis", "Reading", "Sleeping"],
"Games": ["League of Legends", "VALORANT", "Minecraft", "OSU"],
"Owns_Cars": []
})
# Print the data structure
print(InfoDb)
def data(d_rec):
print(d_rec["FirstName"], d_rec["LastName"]) # using comma puts space between values
print("\t", "Residence:", d_rec["Residence"]) # \t is a tab indent
print("\t", "Birth Day:", d_rec["DOB"])
print("\t", "Email:", d_rec["Email"])
print("\t", "Favorite Color:", d_rec["Fav_Color"])
print("\t", "Is Teacher?:", d_rec["is_Teacher"])
print("\t", "Hours of Sleep:", d_rec["Sleep_Schedule"])
print("\t", "Hobbies: " + ", ".join(d_rec["Hobbies"]))
print("\t", "Games: " + ", ".join(d_rec["Games"]))
print("\t", "Cars Owned: " + ", ".join(d_rec["Owns_Cars"]))
print()
# for loop algorithm iterates on length of InfoDb
def for_loop():
print("For loop output\n")
for record in InfoDb:
print_data(record)
for_loop()
def while_loop():
print("While loop output\n")
i = 0
while i < len(InfoDb):
record = InfoDb[i]
print_data(record)
i += 1
return
while_loop()
def reversed_loop(arr):
print("Reversed output of For loop:")
for i in arr[::-1]:
print_data(i)
reversed_loop(InfoDb)
def recursion(i):
if i < len(InfoDb):
record = InfoDb[i]
print_data(record)
recursion(i + 1)
return
print("Recursive loop output\n")
recursion(0)
def add_entry():
name = input("First and last name seperated by spaces: ").split()
gender = input("What is your gender? ")
birthdate = input("When were you born? ")
residence = input("City you live in? ")
email = input("email? ")
color = input("favorite color? ")
sleep = input("When do you go to bed? ")
is_teacher = bool_input("Are you a teacher? [yes/no] ")
hobbies = []
print("hobbies? ")
hobbies = multi_input(hobbies)
games = []
print("Games? ")
games = multi_input(games)
cars = input("What car(s) do you own? ")
entry = {
"FirstName": name[0],
"LastName": name[1],
"Gender": gender,
"DOB": birthdate,
"Residence": residence,
"Email": email,
"Fav_Color": color,
"Sleep_Schedule": sleep,
"is_Teacher": is_teacher,
"Hobbies": hobbies,
"Games" : games,
"Owns_Cars": cars
}
return entry
def bool_input(prompt):
while True:
try:
return {"yes":True,"no":False}[input(prompt).lower()]
except KeyError:
print("Invalid input please enter yes or no")
def multi_input(arr):
i = 0
temp = ""
while temp != "none":
i+=1
temp = input("Please enter item number {0}, type none to proceede ".format(str(i)))
if temp.lower != "none":
arr.append(temp)
return arr
new_entry = add_entry()
InfoDb.append(new_entry)
print(InfoDb[-1])
Questions_Answers = {
"What is 1 + 1 equal to?" : ["2"],
"What is 1 times 1 equal to?" : ["1"],
"What is 1 divided by 1 equal to?" : ["1"],
"What is 1 divided by 0 equal to?" : ["Undefined", "undefined"]
}
def get_pair(dict):
return [q for q, a in dict.items()], [a for q, a in dict.items()]
def percentage(x, y):
return '{0:.2f}'.format(100 * float(x)/float(y))
correct = 0
total = len(Questions_Answers)
Questions_Answers_pairs = get_pair(Questions_Answers)
for i in range(0,len(Questions_Answers_pairs[0])):
rsp = input("Question: " + Questions_Answers_pairs[0][i])
if rsp in Questions_Answers_pairs[1][i]:
print(rsp + " was correct!")
correct+=1
else:
print("{0} was incorrect, the correct answer was: {1}".format(rsp, ", ".join(Questions_Answers_pairs[1][i])))
print("Congratulations, you got {0}% on this quiz".format(percentage(correct,total)))