Lists

Starts with square brackets [], then list the values, quote each value, with commas after each variable

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]))
list [1, 2, 3, 4] <class 'list'> length 4
- list[3] 4 <class 'int'>
langs ['Python', 'JavaScript', 'Java', 'bash'] <class 'list'>
- langs[0] Python <class 'str'>
name = "Evan"
print("What is the value of variable name:", name)
What is the value of variable name: Evan

Notes can be made this way.

Dictionary

Starts with squiggly brackets {} Define data patterns

A list of dictionaries

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)
[{'FirstName': 'Evan', 'LastName': 'Aparri', 'DOB': 'November 10, 2005', 'Residence': 'San Diego', 'Email': 'evanaparri@gmail.com', 'Owns_Cars': 'none', 'Hobbies': ['sleeping']}]


[{'FirstName': 'Evan', 'LastName': 'Aparri', 'DOB': 'November 10, 2005', 'Residence': 'San Diego', 'Email': 'evanaparri@gmail.com', 'Owns_Cars': 'none', 'Hobbies': ['sleeping']}, {'FirstName': 'Sunny', 'LastName': 'Naidu', 'DOB': 'August 2', 'Residence': 'Temecula', 'Email': 'snaidu@powayusd.com', 'Owns_Cars': '4Runner', 'Hobbies': ['eating']}]

Hacks

.append()

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)
[{'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']}, {'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']}, {'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': []}]

For loop

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()
For loop output

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Email: jmortensen@powayusd.com
	 Favorite Color: Unknown
	 Is Teacher?: True
	 Hours of Sleep: Unknown
	 Hobbies: Teaching, Programming
	 Games: 
	 Cars Owned: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Evan Aparri
	 Residence: San Diego
	 Birth Day: November 10, 2005
	 Email: evanaparri@gmail.com
	 Favorite Color: Blue
	 Is Teacher?: False
	 Hours of Sleep: 2am
	 Hobbies: Running, Reading, Eating Asian Food/ Food Connoisseur, Sleeping, Homework, Programming
	 Games: 
	 Cars Owned: 2001-Camry

Alex Lu
	 Residence: San Diego
	 Birth Day: November 29, 2006
	 Email: maodou1258@gmail.com
	 Favorite Color: White
	 Is Teacher?: False
	 Hours of Sleep: 1am
	 Hobbies: Programming, Tennis, Reading, Sleeping
	 Games: League of Legends, VALORANT, Minecraft, OSU
	 Cars Owned: 

Haseeb Beg
	 Residence: san diego
	 Birth Day: december sixth 2007
	 Email: mirzahbeg123@gmail.com
	 Favorite Color: blbue
	 Is Teacher?: False
	 Hours of Sleep: 11pm
	 Hobbies: sleep, none
	 Games: minecraft, none
	 Cars Owned: n, o, n, e

While 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()
While loop output

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Email: jmortensen@powayusd.com
	 Favorite Color: Unknown
	 Is Teacher?: True
	 Hours of Sleep: Unknown
	 Hobbies: Teaching, Programming
	 Games: 
	 Cars Owned: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Evan Aparri
	 Residence: San Diego
	 Birth Day: November 10, 2005
	 Email: evanaparri@gmail.com
	 Favorite Color: Blue
	 Is Teacher?: False
	 Hours of Sleep: 2am
	 Hobbies: Running, Reading, Eating Asian Food/ Food Connoisseur, Sleeping, Homework, Programming
	 Games: 
	 Cars Owned: 2001-Camry

Alex Lu
	 Residence: San Diego
	 Birth Day: November 29, 2006
	 Email: maodou1258@gmail.com
	 Favorite Color: White
	 Is Teacher?: False
	 Hours of Sleep: 1am
	 Hobbies: Programming, Tennis, Reading, Sleeping
	 Games: League of Legends, VALORANT, Minecraft, OSU
	 Cars Owned: 

Printing in reverse

def reversed_loop(arr):
    print("Reversed output of For loop:")
    for i in arr[::-1]:
        print_data(i)

reversed_loop(InfoDb)
Reversed output of For loop:
Haseeb Beg
	 Residence: san diego
	 Birth Day: december sixth 2007
	 Email: mirzahbeg123@gmail.com
	 Favorite Color: blbue
	 Is Teacher?: False
	 Hours of Sleep: 11pm
	 Hobbies: sleep, none
	 Games: minecraft, none
	 Cars Owned: n, o, n, e

Alex Lu
	 Residence: San Diego
	 Birth Day: November 29, 2006
	 Email: maodou1258@gmail.com
	 Favorite Color: White
	 Is Teacher?: False
	 Hours of Sleep: 1am
	 Hobbies: Programming, Tennis, Reading, Sleeping
	 Games: League of Legends, VALORANT, Minecraft, OSU
	 Cars Owned: 

Evan Aparri
	 Residence: San Diego
	 Birth Day: November 10, 2005
	 Email: evanaparri@gmail.com
	 Favorite Color: Blue
	 Is Teacher?: False
	 Hours of Sleep: 2am
	 Hobbies: Running, Reading, Eating Asian Food/ Food Connoisseur, Sleeping, Homework, Programming
	 Games: 
	 Cars Owned: 2001-Camry

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Email: jmortensen@powayusd.com
	 Favorite Color: Unknown
	 Is Teacher?: True
	 Hours of Sleep: Unknown
	 Hobbies: Teaching, Programming
	 Games: 
	 Cars Owned: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Recursion

def recursion(i):
    if i < len(InfoDb):
        record = InfoDb[i]
        print_data(record)
        recursion(i + 1)
    return
    
print("Recursive loop output\n")
recursion(0)
Recursive loop output

John Mortensen
	 Residence: San Diego
	 Birth Day: October 21
	 Email: jmortensen@powayusd.com
	 Favorite Color: Unknown
	 Is Teacher?: True
	 Hours of Sleep: Unknown
	 Hobbies: Teaching, Programming
	 Games: 
	 Cars Owned: 2015-Fusion, 2011-Ranger, 2003-Excursion, 1997-F350, 1969-Cadillac

Evan Aparri
	 Residence: San Diego
	 Birth Day: November 10, 2005
	 Email: evanaparri@gmail.com
	 Favorite Color: Blue
	 Is Teacher?: False
	 Hours of Sleep: 2am
	 Hobbies: Running, Reading, Eating Asian Food/ Food Connoisseur, Sleeping, Homework, Programming
	 Games: 
	 Cars Owned: 2001-Camry

Alex Lu
	 Residence: San Diego
	 Birth Day: November 29, 2006
	 Email: maodou1258@gmail.com
	 Favorite Color: White
	 Is Teacher?: False
	 Hours of Sleep: 1am
	 Hobbies: Programming, Tennis, Reading, Sleeping
	 Games: League of Legends, VALORANT, Minecraft, OSU
	 Cars Owned: 

Haseeb Beg
	 Residence: san diego
	 Birth Day: december sixth 2007
	 Email: mirzahbeg123@gmail.com
	 Favorite Color: blbue
	 Is Teacher?: False
	 Hours of Sleep: 11pm
	 Hobbies: sleep, none
	 Games: minecraft, none
	 Cars Owned: n, o, n, e

Adding to the List using Input

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])
hobbies? 
Games? 
{'FirstName': 'Haseeb', 'LastName': 'Beg', 'Gender': 'male', 'DOB': 'december sixth 2007', 'Residence': 'san diego', 'Email': 'mirzahbeg123@gmail.com', 'Fav_Color': 'blbue', 'Sleep_Schedule': '11pm', 'is_Teacher': False, 'Hobbies': ['sleep', 'none'], 'Games': ['minecraft', 'none'], 'Owns_Cars': 'none'}

Quiz

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)))
2 was correct!
1 was correct!
0 was incorrect, the correct answer was: 1
undefined was correct!
Congratulations, you got 75.00% on this quiz