Variables

Variables all have a type:String, Integer, Float, List and Dictionary are some key types.

name = "Vivian Ni"
print("name", name, type(name))

print()

# variable of type integer
age = 16
print("age", age, type(age))

print()

# variable of type float
score = 3.00
print("score", score, type(score))

print()

# variable of type list (many values in one variable)
langs = ["Python", "JavaScript", "Java", "bash"]
print("langs", langs, type(langs), "length", len(langs))
print("- langs[3]", langs[3], type(langs[3]))

print()

# variable of type dictionary (a group of keys and values)
person = {
    "name": name,
    "age": age,
    "score": score,
    "langs": langs
}
print("person", person, type(person), "length", len(person))
print('- person["name"]', person["name"], type(person["name"]))
name Vivian Ni <class 'str'>

age 16 <class 'int'>

score 3.0 <class 'float'>

langs ['Python', 'JavaScript', 'Java', 'bash'] <class 'list'> length 4
- langs[3] bash <class 'str'>

person {'name': 'Vivian Ni', 'age': 16, 'score': 3.0, 'langs': ['Python', 'JavaScript', 'Java', 'bash']} <class 'dict'> length 4
- person["name"] Vivian Ni <class 'str'>

List of Dictionaries

this code appends the dictionaries to the list, the list being infoDb. As you can see, 2 dictionaries have been appended.

infoDb = []

# Append to List a Dictionary of key/values 
infoDb.append({
    "FirstName": "Vivian",
    "LastName": "Ni",
    "DOB": "May 13",
    "Residence": "San Diego",
    "Fav_Movie": "Inception",
    "Email": "vivianni452@gmail.com",
    "Best_Treats": ["cookies", "ice cream", "cake", "brownies"]
})

infoDb.append({
    "FirstName": "Emma",
    "LastName": "Shen",
    "DOB": "July 29",
    "Residence": "San Diego",
    "Email": "aimashen.2017@gmail.com",
    "Fav_Movie": "MIB",
    "Best_Treats": ["smoothies", "ice cream"]
})

# Print the data structure
print(infoDb)
[{'FirstName': 'Vivian', 'LastName': 'Ni', 'DOB': 'May 13', 'Residence': 'San Diego', 'Fav_Movie': 'Inception', 'Email': 'vivianni452@gmail.com', 'Best_Treats': ['cookies', 'ice cream', 'cake', 'brownies']}, {'FirstName': 'Emma', 'LastName': 'Shen', 'DOB': 'July 29', 'Residence': 'San Diego', 'Email': 'aimashen.2017@gmail.com', 'Fav_Movie': 'MIB', 'Best_Treats': ['smoothies', 'ice cream']}]

For Loop for output of List/Dictionary

takes the dictionaries in the list and prints them

def for_loop():
    print("For loop output\n")
    for record in infoDb:
        print(record)

for_loop()
For loop output

{'FirstName': 'Vivian', 'LastName': 'Ni', 'DOB': 'May 13', 'Residence': 'San Diego', 'Fav_Movie': 'Inception', 'Email': 'vivianni452@gmail.com', 'Best_Treats': ['cookies', 'ice cream', 'cake', 'brownies']}
{'FirstName': 'Emma', 'LastName': 'Shen', 'DOB': 'July 29', 'Residence': 'San Diego', 'Email': 'aimashen.2017@gmail.com', 'Fav_Movie': 'MIB', 'Best_Treats': ['smoothies', 'ice cream']}

Alternate Methods of Iteration

Formatted Output of Dictionaries: Using For Loop with an Index

this code uses a for loop with the range and index syntax to print the dictionaries. It also does so in reverse order

Formatted output of Dictionary Managing data in Lists and Dictionaries is for the convenience of passing the data across the internet or preparing it to be stored into a database. Also, it is a great way to exchange data inside of our own programs.

Next, we will take the stored data and output it within our notebook. There are multiple steps to this process.

Preparing a function to format the data, the print_data() function receives a parameter called "d_rec" short for dictionary record. It then references different keys within [] square brackets. Preparing a function to iterate through the list, the for_loop() function uses an enhanced for loop that pull record by record out of InfoDb until the list is empty. Each time through the loop it call print_data(record), which passes the dictionary record to that function. Finally, you need to activate your function with the call to the defined function for_loop(). Functions are defined, not activated until they are called. By placing for_loop() at the left margin the function is activated.

def print_data(d_rec): #formatting
    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", "Favorite Movie", d_rec["Fav_Movie"])
    print("\t", "Email:", d_rec["Email"])
    print("\t", "Best Treats: ", end="")  # end="" make sure no return occurs
    print(", ".join(d_rec["Best_Treats"]))  # join allows printing a string list with separator
    print()

# for loop iterates on length of InfoDb
def for_loop():
    print("For loop with index output\n")
    length = len(infoDb) #figures out the length of the list infoDb (which is 2 because there are 2 dictionaries in the list)
    ran = range(length) #defines ran as the range of the length. (this is 0 and 1 because the length is 2)
    for index in reversed(ran): #index is 0 and 1 so it takes the indexes of infoDb. 0 would be the first dictionary and 1 would be the second. reversed prints them as 1 0 instead of 0 1
        print_data(infoDb[index])

for_loop()
For loop with index output

Emma Shen
	 Residence: San Diego
	 Birth Day: July 29
	 Favorite Movie MIB
	 Email: aimashen.2017@gmail.com
	 Best Treats: smoothies, ice cream

Vivian Ni
	 Residence: San Diego
	 Birth Day: May 13
	 Favorite Movie Inception
	 Email: vivianni452@gmail.com
	 Best Treats: cookies, ice cream, cake, brownies

While Loop

contains a while loop, "while i < len(InfoDb):". This counts through the elements in the list start at zero, and passes the record to print_data()

def while_loop():
    print("While loop output\n")
    i = 0 
    while i < len(infoDb): #length is 2 so while i is less than, it will keep printing
        record = infoDb[i] #defines the record as the index of the list
        print_data(record) #prints that index using the formatted print function
        i += 1 #adds 1 and returns to the top till i is no longer <2
    return

while_loop()
While loop output

Vivian Ni
	 Residence: San Diego
	 Birth Day: May 13
	 Favorite Movie Inception
	 Email: vivianni452@gmail.com
	 Best Treats: cookies, ice cream, cake, brownies

Emma Shen
	 Residence: San Diego
	 Birth Day: July 29
	 Favorite Movie MIB
	 Email: aimashen.2017@gmail.com
	 Best Treats: smoothies, ice cream

Recursion

this method calls itself repeatedly until the "if i < len(infoDb)" is no longer true. the recursive_loop(0) is set at the start and it keeps activating a new call as recursive_loop(i + 1)

def recursive_loop(i):
    if i < len(infoDb): #ensures the code stops after it recurses through all the indexes since length determines amount of indexes
        record = infoDb[i] #defines record as the index of infoDb
        print_data(record) #prints using the formatted print function
        recursive_loop(i + 1) #adds 1 to the original index and returns until i is no longer <2
    return
    
print("Recursive loop output\n")

recursive_loop(0)
Recursive loop output

Vivian Ni
	 Residence: San Diego
	 Birth Day: May 13
	 Favorite Movie Inception
	 Email: vivianni452@gmail.com
	 Best Treats: cookies, ice cream, cake, brownies

Emma Shen
	 Residence: San Diego
	 Birth Day: July 29
	 Favorite Movie MIB
	 Email: aimashen.2017@gmail.com
	 Best Treats: smoothies, ice cream

Using Input to Add/Search/Delete Dictionaries

from asyncio.windows_events import NULL

infoDb = []

infoDb.append({
    "FirstName": "Vivian",
    "LastName": "Ni",
    "DOB": "May 13",
    "Residence": "San Diego",
    "Fav_Movie": "Inception",
    "Email": "vivianni452@gmail.com",
})

infoDb.append({
    "FirstName": "Hanli",
    "LastName": "Ni",
    "DOB": "Jan 11",
    "Residence": "San Diego",
    "Email": "hanlini@gmail.com",
    "Fav_Movie": "Interstellar",
})

def print_data2(d_rec): #formatting
    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", "Favorite Movie:", d_rec["Fav_Movie"])
    print("\t", "Email:", d_rec["Email"])
    print()

def data_entry(): #defining the function that asks for user input
    Firstname = input("What is your firstname?")
    Lastname = input("What is your lastname")
    DOB = input("When is your birthday")
    Email = input("What is your Email")
    Movie = input("What is your favorite movie?")
    Residence = input("Where do you live?")

    infoDb.append({ #appends the user input to the dictionary
        "FirstName": Firstname,
        "LastName": Lastname,
        "DOB": DOB,
        "Email": Email,
        "Residence": Residence,
        "Fav_Movie": Movie,
   
    })

def search_data(firstname):
    for record in infoDb:
        if record["FirstName"] == firstname: #compares the already existing name to the name inputted with the firstname variable
            return record

    return NULL

def data_delete(firstname):
    record = search_data(firstname) #defines record as the name inputted with the search function
    if (record != NULL): #if the record doesn't equal null (does it exist?) then the next line removes it
        infoDb.remove(record)
        print(firstname, "has been deleted!")
    else:
        print("Record not found!")

def main():
    Continue = True #defining continue as true
    while Continue:
        lol = input("What would you like to do (add/search/delete, type no if you want to exit)?")
        if lol == "no":
            print("Come back again!")
            Continue = False
        elif lol == "add":
            data_entry()
        elif lol == "search":
            firstname = input("Who do you want to search (firstname)?")
            record = search_data(firstname) #defines record as the input "name" and runs it through the search function
            print_data2(record)
        elif lol == "delete":
            firstname = input("Who do you want to delete(firstname)")
            data_delete(firstname)
        else:
            print("Invalid input. Please try again")

    length = len(infoDb) #defines length as the number of records
    print("Total Number of Records: ", length) 
    for record in infoDb:
            print_data2(record)
 
main()
Hanli is deleted!
Come back again!
Total Number of Records:  2
Vivian Ni
	 Residence: San Diego
	 Birth Day: May 13
	 Favorite Movie Inception
	 Email: vivianni452@gmail.com

Emma Shen
	 Residence: San Diego
	 Birth Day: July
	 Favorite Movie Not sure
	 Email: aimashen.2017@gmail.com

Quiz that stores in a List of Dictionaries

questions = 5
correct = 0

print("Take this fun quiz on food!")

def question_and_answer(prompt, answer):
    print("Question: " + prompt)
    msg = input()
    print("Answer: " + msg)
    
    if answer == msg.lower():
        print("Correct!")
        global correct
        correct += 1
    else:
        print ("Incorrect!")
        
    return msg
 
Q1 = question_and_answer("Which famous soft drink was invented in 1892?? \t Coca cola \t pepsi \t rootbeer", "coca cola")
Q2 = question_and_answer("What was the first food eaten in space? \t applesauce \t icecream  \t mashed potatoes", "applesauce")
Q3 = question_and_answer("Where were French fries invented? \t France \t America \t Belgium", "Belgium")
Q4 = question_and_answer("What is the USA’s favorite flavor of ice cream? \t chocolate  \t vanilla  \t strawberry", "vanilla")
Q5 = question_and_answer("What is the most popular pizza topping in the USA? \t pepperoni \t sausage \t olives", "pepperoni")

print(f'You scored {correct} /5 correct answers!')
    
Quiz = {
    "Question 1": Q1,
    "Question 2": Q2,
    "Question 3": Q3,
    "Question 4": Q4,
    "Question 5": Q5
}

print("Here is a record of your quiz answers:",Quiz)
Take this fun quiz on food!
Question: Which famous soft drink was invented in 1892?? 	 Coca cola 	 pepsi 	 rootbeer
Answer: coca cola
Correct!
Question: What was the first food eaten in space? 	 applesauce 	 icecream  	 mashed potatoes
Answer: applesauce
Correct!
Question: Where were French fries invented? 	 France 	 America 	 Belgium
Answer: belgium
Incorrect!
Question: What is the USA’s favorite flavor of ice cream? 	 chocolate  	 vanilla  	 strawberry
Answer: vanilla
Correct!
Question: What is the most popular pizza topping in the USA? 	 pepperoni 	 sausage 	 olives
Answer: pepperoni
Correct!
You scored 4 /5 correct answers!
Here is a record of your quiz answers: {'Question 1': 'coca cola', 'Question 2': 'applesauce', 'Question 3': 'belgium', 'Question 4': 'vanilla', 'Question 5': 'pepperoni'}