Lists, Dictionaries, Iteration
- Defining InfoDB
- Adding entries to InfoDB
- Printing InfoDB
- For loop with index
- While loop
- Recursion
- Adding an entry to InfoDB with user input
- My partner's list
- Modified format_entry for Alex's list
- A quiz using "a list of dictionaries" (?)
- Print list backwards
InfoDb = []
InfoDb.append({
# key-value pairs
"name": "Safin Singh",
"age": 16,
"phone": "858-XXX-XXXX",
# interests is a list of strs
"interests": ["tennis", "programming"],
# grades is a dict
"grades": {
"APCSP": "A",
"APEL": "A",
"AP Physics": "A",
"AP Stats": "A"
}
})
InfoDb.append({
"name": "Alex Kumar",
"age": 16,
"phone": "858-XXX-XXXX",
"interests": ["basketball"],
"grades": {
"APCSP": "A",
"APEL": "A",
"AP Physics": "A",
"AP Calculus BC": "A"
}
})
InfoDb.append({
"name": "Kalani Cabral-Omana",
"age": 16,
"phone": "619-XXX-XXXX",
"interests": ["soccer", "surfing"],
"grades": {
"APCSP": "A",
"APEL": "B",
"AP Physics": "B",
"AP Stats": "A"
}
})
InfoDb.append({
"name": "Navan Yatavelli",
"age": 15,
"phone": "858-XXX-XXXX",
"interests": ["football", "walking my dog"],
"grades": {
"APCSP": "A",
"American Lit": "A",
"AP Stats": "A",
"AP Bio": "A"
}
})
def format_entry(entry):
# use format string to print entries
print("""{}
Age: {}
Phone: {}
Interests: {}
Grades:""".format(entry["name"], entry["age"], entry["phone"], ", ".join(entry["interests"])))
# loop through classes to print each individual grade
for cl, grade in entry["grades"].items():
print(" {}: {}".format(cl, grade))
print()
# loop through each entry in InfoDb by value
for entry in InfoDb:
format_entry(entry)
for i in range(len(InfoDb)):
# access the element at index i of InfoDb
format_entry(InfoDb[i])
i = 0
# cap the loop at len(InfoDb) runs
n = len(InfoDb)
# while the counter is less than list length...
while i < n:
# print entry at index i
format_entry(InfoDb[i])
# increment counter
i+=1
n = len(InfoDb)
# define recursive function
def printer(i):
# if you are at the end of the list, quit
if i == n:
return
# print entry at index i
format_entry(InfoDb[i])
# call function with the next index
printer(i+1)
# call function starting at index 0
printer(0)
name = input("What's your name? ")
age = int(input("How old are you? "))
phone = input("What's your phone number? ")
# get interests as a comma-separated list and split on the comma
interests = input("What are your interests (comma-separated)? ").split(",")
# see above
classes = input("What classes are you in (comma-separated)? ").split(",")
grades = input(
"What are your grades in each of your respective classes (comma-separated)? ").split(",")
# transform both arrays into an array of tuples and then to a dict
class_grades = dict(zip(classes, grades))
InfoDb.append({
"name": name,
"age": age,
"phone": phone,
"interests": interests,
"grades": class_grades
})
InfoDb = []
InfoDb.append({
"FirstName": "samit",
"LastName": "poojary",
"DOB": "September 15",
"Residence": "San Diego",
"Email": "samit.poojary@gmail.com",
"Phone": "iphone"
})
#adding extra records to InfoDb
InfoDb.append({
"FirstName": "Safin",
"LastName": "Singh",
"DOB": "July 13",
"Residence": "San Diego",
"Email": "safin.singh@gmail.com",
"Phone": "android"
})
# adding extra records
InfoDb.append({
"FirstName": "Alex",
"LastName": "Kumar",
"DOB": "May 9",
"Residence": "San Diego",
"Email": "alex.k.kumar@gmail.com",
"Phone": "iphone"
})
# Adding one extra item to InfoDb
InfoDb.append({
"FirstName": "Maxie",
"LastName": "Kumar",
"DOB": "November 5",
"Residence": "San Diego",
"Email": "maxie.kumar@gmail.com",
"Phone": "no phone"
})
def format_entry(entry):
# use format string to print entries
print("""{} {}
Date of Birth: {}
Residence: {}
Email: {}
Phone:""".format(
entry["FirstName"],
entry["LastName"],
entry["DOB"],
entry["Residence"],
entry["Email"],
entry["Phone"]
))
def ask(qna):
# get question and answer from qna dictionary
question = qna.keys()[0]
# get user input
res = input(question + " ")
# make comparison case-insensitive (given our answers are lowercase)
if res.lower() == qna[question]:
# use string interpolation to print a correct anser
print("'{}' is the correct answer!".format(res))
return True
else:
# prompt the user to try again if they want to
again = input("'{}' is incorrect. Try again? [y/N] ".format(res))
if again == "y":
# recursively call "ask" function for the retry feature
return ask(qna)
else:
return False
questions_and_answer = [
# questions taken from previous quiz
{"What command is used to include other functions that were previously developed?": "import"},
{"What command is used to evaluate correct or incorrect response in this example?": "if"},
{"Each 'if' command contains an '_________' to determine a true or false condition?": "expression"},
{"The two possible boolean values in Python are true and '____'.": "false"},
{"Python is a(n) [interpreted/compiled] language.": "interpreted"},
{"A '___' loop can iterate over items in a list.": "for"},
{"What keyword can be used to create a block that can catch and handle an exception?": "try"},
{"A function '________' allows the programmer to specify additional info to a function.": "parameter"},
{"The 'def' keyword is used when defining a '________'.": "function"},
{"The '_' operator can be used to concatenate two strings.": "+" }
]
# counter for the total correct answers
correct = 0
# loop over all items in the questions_and_answers list
for qna in questions_and_answer:
if ask(qna):
# increment the counter if the user gets something correct
correct += 1
# display the total score at the end with an encouraging message
print("Great job! You got a score of {}%.".format(
int(100 * correct / len(questions_and_answer))))
for entry in InfoDb[::-1]:
format_entry(entry)