Variable

Variables have types :string, integer, and float. Lists and Dictionaries is a key type!

name = "Luna Iwazaki"
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 Luna Iwazaki <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': 'Luna Iwazaki', 'age': 16, 'score': 3.0, 'langs': ['Python', 'JavaScript', 'Java', 'bash']} <class 'dict'> length 4
- person["name"] Luna Iwazaki <class 'str'>

Dictionaires

infoDb = []

# Append to List a Dictionary of key/values 
infoDb.append({
    "FirstName": "Luna",
    "LastName": "Iwazaki",
    "DOB": "November 19",
    "Residence": "San Diego",
    "Fav_Game": "Snake",
    "Email": "lunaiwazaki@gmail.com",
    "Shapes": ["heart", "circle", "star"]
})

infoDb.append({
    "FirstName": "Taiyo",
    "LastName": "Iwazaki",
    "DOB": "Novemebr 19",
    "Residence": "San Diego",
    "Email": "taiyoiwazaki@gmail.com",
    "Fav_Game": "Valorent",
    "Shapes": ["square", "circle", "triangle"]
})

# Print the data structure
print(infoDb)
[{'FirstName': 'Luna', 'LastName': 'Iwazaki', 'DOB': 'November 19', 'Residence': 'San Diego', 'Fav_Game': 'Snake', 'Email': 'lunaiwazaki@gmail.com', 'Shapes': ['heart', 'circle', 'star']}, {'FirstName': 'Taiyo', 'LastName': 'Iwazaki', 'DOB': 'Novemebr 19', 'Residence': 'San Diego', 'Email': 'taiyoiwazaki@gmail.com', 'Fav_Game': 'Valorent', 'Shapes': ['square', 'circle', 'triangle']}]

Loop Output

List printing

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

for_loop()
For loop output

{'FirstName': 'Luna', 'LastName': 'Iwazaki', 'DOB': 'November 19', 'Residence': 'San Diego', 'Fav_Game': 'Snake', 'Email': 'lunaiwazaki@gmail.com', 'Shapes': ['heart', 'circle', 'star']}
{'FirstName': 'Taiyo', 'LastName': 'Iwazaki', 'DOB': 'Novemebr 19', 'Residence': 'San Diego', 'Email': 'taiyoiwazaki@gmail.com', 'Fav_Game': 'Valorent', 'Shapes': ['square', 'circle', 'triangle']}

Loops and Index

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", "Game", d_rec["Fav_Game"])
    print("\t", "Email:", d_rec["Email"])
    print("\t", "Shapes: ", end="")  # end="" make sure no return occurs
    print(", ".join(d_rec["Shapes"]))  # 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

Taiyo Iwazaki
	 Residence: San Diego
	 Birth Day: Novemebr 19
	 Game Valorent
	 Email: taiyoiwazaki@gmail.com
	 Shapes: square, circle, triangle

Luna Iwazaki
	 Residence: San Diego
	 Birth Day: November 19
	 Game Snake
	 Email: lunaiwazaki@gmail.com
	 Shapes: heart, circle, star

While Loop Output

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

Luna Iwazaki
	 Residence: San Diego
	 Birth Day: November 19
	 Game Snake
	 Email: lunaiwazaki@gmail.com
	 Shapes: heart, circle, star

Taiyo Iwazaki
	 Residence: San Diego
	 Birth Day: Novemebr 19
	 Game Valorent
	 Email: taiyoiwazaki@gmail.com
	 Shapes: square, circle, triangle

Recursive Loop

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

Luna Iwazaki
	 Residence: San Diego
	 Birth Day: November 19
	 Game Snake
	 Email: lunaiwazaki@gmail.com
	 Shapes: heart, circle, star

Taiyo Iwazaki
	 Residence: San Diego
	 Birth Day: Novemebr 19
	 Game Valorent
	 Email: taiyoiwazaki@gmail.com
	 Shapes: square, circle, triangle

Add-Search-Delete

infoDb.append({
    "FirstName": "Luna",
    "LastName": "Iwazaki",
    "DOB": "Novemeber 19",
    "Residence": "San Diego",
    "Fav_Game": "Snake",
    "Email": "lunaiwazaki@gmail.com",
})

infoDb.append({
    "FirstName": "Taiyo",
    "LastName": "Iwazaki",
    "DOB": "Novemeber 19",
    "Residence": "San Diego",
    "Email": "taiyoiwazaki@gmail.com",
    "Fav_Game": "Valorent",
})

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 Game:", d_rec["Fav_Game"])
    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 game?")
    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_Game": 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()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb Cell 15 in <cell line: 1>()
----> <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=0'>1</a> infoDb.append({
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=1'>2</a>     "FirstName": "Luna",
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=2'>3</a>     "LastName": "Iwazaki",
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=3'>4</a>     "DOB": "Novemeber 19",
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=4'>5</a>     "Residence": "San Diego",
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=5'>6</a>     "Fav_Game": "Snake",
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=6'>7</a>     "Email": "lunaiwazaki@gmail.com",
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=7'>8</a> })
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=9'>10</a> infoDb.append({
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=10'>11</a>     "FirstName": "Taiyo",
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=11'>12</a>     "LastName": "Iwazaki",
   (...)
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=15'>16</a>     "Fav_Game": "Valorent",
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=16'>17</a> })
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X20sZmlsZQ%3D%3D?line=18'>19</a> def print_data2(d_rec): #formatting

NameError: name 'infoDb' is not defined

Quiz

questions = 5
correct = 0

print("Take this quiz to test your vocab!")

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("What is the definition of INPUT? \t instructions given to a computer \t computer paper \t paper instructions", "instructions given to a computer")
Q2 = question_and_answer("What is a squence? \t a line of code \t several lines of code  \t a button", "several lines of code")
Q3 = question_and_answer("What is an output? \t information a computer gives \t a computer tab \t going outside", "information a computer gives")
Q4 = question_and_answer("What does a variable do? \t gives variety \t a way to store your paper files \t way to name, store data, and reference data", "way to name, store data, and reference data")
Q5 = question_and_answer("What are lists? \t something for the grocery \t the square brackets for grouping and ordering \t a square", "the square brackets for grouping and ordering")

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 quiz to test your vocab!
Question: What is the definition of INPUT? 	 instructions given to a computer 	 computer paper 	 paper instructions
Answer: instructions given to a computer
Correct!
Question: What is a squence? 	 a line of code 	 several lines of code  	 a button
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb Cell 17 in <cell line: 21>()
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=17'>18</a>     return msg
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=19'>20</a> Q1 = question_and_answer("What is the definition of INPUT? \t instructions given to a computer \t computer paper \t paper instructions", "instructions given to a computer")
---> <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=20'>21</a> Q2 = question_and_answer("What is a squence? \t a line of code \t several lines of code  \t a button", "several lines of code")
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=21'>22</a> Q3 = question_and_answer("What is an output? \t information a computer gives \t a computer tab \t going outside", "information a computer gives")
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=22'>23</a> Q4 = question_and_answer("What does a variable do? \t gives variety \t a way to store your paper files \t way to name, store data, and reference data", "way to name, store data, and reference data")

/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb Cell 17 in question_and_answer(prompt, answer)
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=5'>6</a> def question_and_answer(prompt, answer):
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=6'>7</a>     print("Question: " + prompt)
----> <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=7'>8</a>     msg = input()
      <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=8'>9</a>     print("Answer: " + msg)
     <a href='vscode-notebook-cell:/Users/sony/iwazaki-1/_notebooks/2022-09-05-Lists-and-Dictionaries.ipynb#X22sZmlsZQ%3D%3D?line=10'>11</a>     if answer == msg.lower():

File /Applications/anaconda3/lib/python3.9/site-packages/ipykernel/kernelbase.py:1177, in Kernel.raw_input(self, prompt)
   1173 if not self._allow_stdin:
   1174     raise StdinNotImplementedError(
   1175         "raw_input was called, but this frontend does not support input requests."
   1176     )
-> 1177 return self._input_request(
   1178     str(prompt),
   1179     self._parent_ident["shell"],
   1180     self.get_parent("shell"),
   1181     password=False,
   1182 )

File /Applications/anaconda3/lib/python3.9/site-packages/ipykernel/kernelbase.py:1219, in Kernel._input_request(self, prompt, ident, parent, password)
   1216             break
   1217 except KeyboardInterrupt:
   1218     # re-raise KeyboardInterrupt, to truncate traceback
-> 1219     raise KeyboardInterrupt("Interrupted by user") from None
   1220 except Exception:
   1221     self.log.warning("Invalid Message:", exc_info=True)

KeyboardInterrupt: Interrupted by user