Running the Code

I ran the given code from the APCSP website. I hypothesize that strings, floats, and integers are primitive, as they are simpler, and usually one value. This means that dictionaries and lists are collections, as they are a collection of multiple values.

print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
name = "John Doe"
print("name", name, type(name))

print()


# variable of type integer
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
age = 18
print("age", age, type(age))

print()

# variable of type float
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
score = 90.0
print("score", score, type(score))

print()

# variable of type list (many values in one variable)
print("What is variable name/key?", "value?", "type?", "primitive or collection?")
print("What is different about the list output?")
langs = ["Python", "JavaScript", "Java"]
print("langs", langs, type(langs), "length", len(langs))
print("- langs[0]", langs[0], type(langs[0]))

print()

# variable of type dictionary (a group of keys and values)
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
print("What is different about the dictionary output?")
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"]))

print(langs[1]) # Will output "Java"
print
What is the variable name/key? value? type? primitive or collection, why?
name John Doe <class 'str'>

What is the variable name/key? value? type? primitive or collection, why?
age 18 <class 'int'>

What is the variable name/key? value? type? primitive or collection, why?
score 90.0 <class 'float'>

What is variable name/key? value? type? primitive or collection?
What is different about the list output?
langs ['Python', 'JavaScript', 'Java'] <class 'list'> length 3
- langs[0] Python <class 'str'>

What is the variable name/key? value? type? primitive or collection, why?
What is different about the dictionary output?
person {'name': 'John Doe', 'age': 18, 'score': 90.0, 'langs': ['Python', 'JavaScript', 'Java']} <class 'dict'> length 4
- person["name"] John Doe <class 'str'>

Using Append

Using the .append() function to add more information. Using InfoDb from the APCSP repository. Additionally, this demonstrates using user input to add information to InfoDb.

InfoDb = []

# InfoDB is a data structure with expected Keys and Values

# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
    "FirstName": "John",
    "LastName": "Mortensen",
    "DOB": "October 21",
    "Residence": "San Diego",
    "Email": "jmortensen@powayusd.com",
    "Owns_Cars": ["2015-Fusion", "2011-Ranger", "2003-Excursion", "1997-F350", "1969-Cadillac"]
})

# 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"]
})

# My information
InfoDb.append({
    "FirstName": "Arnav",
    "LastName": "Kanekar",
    "DOB": "July 3",
    "Residence": "San Diego",
    "Email": "**********@*****.***", # Censored
    "Owns_Cars": "None"
})

# Using input to add information to the dictionary
InfoDb.append({
    "FirstName": input("What is your first name?"),
    "LastName": input("What is your last name?"),
    "DOB": input("What is your date of birth(Month, day)?"),
    "Residence": input("Where do you live?"),
    "Email": input("What is your email?"), 
    "Owns_Cars": input("What cars do you own?")
})

# Print the data structure
print(InfoDb)
[{'FirstName': 'John', 'LastName': 'Mortensen', 'DOB': 'October 21', 'Residence': 'San Diego', 'Email': 'jmortensen@powayusd.com', 'Owns_Cars': ['2015-Fusion', '2011-Ranger', '2003-Excursion', '1997-F350', '1969-Cadillac']}, {'FirstName': 'Sunny', 'LastName': 'Naidu', 'DOB': 'August 2', 'Residence': 'Temecula', 'Email': 'snaidu@powayusd.com', 'Owns_Cars': ['4Runner']}, {'FirstName': 'Arnav', 'LastName': 'Kanekar', 'DOB': 'July 3', 'Residence': 'San Diego', 'Email': '**********@*****.***', 'Owns_Cars': 'None'}, {'FirstName': 'John', 'LastName': 'Cena', 'DOB': 'April 23', 'Residence': 'Tampa', 'Email': 'johncena@gmail.com', 'Owns_Cars': '2006 Ford GT, 1970 Plymouth Superbird'}]

For Loops

Using a for loop to iterate through a list.

sports = ["football", "track", "soccer", "basketball", "tennis"] # list
# iterates based on the range, so in this case it will only iterate 5 times
for i in range(5):
    print(sports[i]) # would not print more than 5 sports, even if list is longer
football
track
soccer
basketball
tennis

For Loop with an Index

Creating a list and using a for loop with indexes to print it. This iterates for every index in the list, making it more powerful and easier to code with.

cake_flavors = ["chocolate", "strawberry", "vanilla"] # List
# For loop, for index in list
for i in cake_flavors:
    print(i) # Print the flavor
chocolate
strawberry
vanilla

Using the While Loop and Inputs

This demonstrates usage of the while loop. The while loop calls a function as long as a certain condition is met. This is also another example of creating dictionaries using inputs.

meals = {} # empty dictionary

length = 4

# runs as long as there are less than 4 items in the dictionary
while len(meals) < length:
    name = input("Name a food.")
    rating = input("How would you rate the meal on a scale of 1 - 10?")
    meals[name] = rating # determines the key and the value

print(meals)
{'pineapple pizza': '5', 'chicken alfredo': '8', 'fried chicken': '10', 'mango': '9'}

Recursion

Recursive functions are helpful, but can be inefficient since it keeps on recalling the function.

def factorial(i): # defining the function
    if i == 0: # will not recall function
        return 1
    if i == 1: # will not recall function
        return i
    if i != 1:
        return i * factorial(i - 1) # recalls the function, but at lesser value

print(factorial(5))
print(factorial(0))
print(factorial(1))
120
1
1

Tools

Using other capabilities to organize lists. These are very useful tools.

Reverse Order

Command to output a list in reverse order.

countdown = [3, 2, 1] # New list
print(countdown)
countdown.reverse() # Reversing the list
print(countdown)
[3, 2, 1]
[1, 2, 3]

This shows that the .reverse() statement is used to reverse a list.

Sort and Set

More functions that can help to alphabetize lists as well as make sure there are no duplicates in the list.

cake_flavors = ["chocolate", "strawberry", "vanilla"]
# Appending multiple items
cake_flavors.append("red velvet")
cake_flavors.append("lemon")
cake_flavors.append("marble")

print(cake_flavors) # Printing the new list

# Sort function
cake_flavors.sort()
print(cake_flavors) # Alphabetized list

# Appending more flavors
cake_flavors.append("lemon")
cake_flavors.append("german chocolate")
cake_flavors.append("carrot")

print(cake_flavors)

cake_flavors = set(cake_flavors)

print(cake_flavors)
['chocolate', 'strawberry', 'vanilla', 'red velvet', 'lemon', 'marble']
['chocolate', 'lemon', 'marble', 'red velvet', 'strawberry', 'vanilla']
['chocolate', 'lemon', 'marble', 'red velvet', 'strawberry', 'vanilla', 'lemon', 'german chocolate', 'carrot']
{'red velvet', 'carrot', 'marble', 'vanilla', 'german chocolate', 'chocolate', 'lemon', 'strawberry'}

Showcases the .append(), .sort(), and set(). Append adds a new item to the list, sort puts the list in alphabetical order, and set removes any duplicatte items.

Quiz

Creating a quiz like last week, except using a list of dictionaries. This makes it easier to store questions and answers as key and value pairs.

quiz = [] # empty list

#variables
question_count = 5
score = 0

# appending some questions
quiz.append({
    "What type of language is Python" : "object oriented",
    "How do you get an output in Python?" : "print"
})

quiz.append({
    "Is a dictionary a primitive or a collection?" : "collection",
    "How do you add more information to a list?" : "append",
    "What do you need to call to get the value in a dictionary?" : "key"
})

# function to print questions and get answers
def questioning(ask):
    print("Question: " + ask)
    global ans
    ans = input()
    print("Answer: " + ans)

# for loop to iterate through the dictionary
for dict in quiz:
    for question, answer in dict.items(): # for the key and value pair
        questioning(question) # calling function
        if ans.lower() == answer:
            score += 1
            print("Your answer is correct.")
        else:
            print("You are incorrect.")

# percentage calculator from last time
def grade(sco, quests): 
    percent = 100 * float(sco)/float(quests)
    return percent

quiz_percentage = grade(score, question_count) # Defining variable

print("You got " + str(score) + " of " + str(question_count) + " questions correct.")
print("Your score is " + str(quiz_percentage) + "%.")
Question: What type of language is Python
Answer: OBJECT ORiented
Your answer is correct.
Question: How do you get an output in Python?
Answer: pRINT
Your answer is correct.
Question: Is a dictionary a primitive or a collection?
Answer: primitive
You are incorrect.
Question: How do you add more information to a list?
Answer: APPEnd
Your answer is correct.
Question: What do you need to call to get the value in a dictionary?
Answer: kEY
Your answer is correct.
You got 4 of 5 questions correct.
Your score is 80.0%.