Variables & Assignments and Data Abstraction Lesson Notes
Based on the presentation by Tay, Aditya, Rohan, and Dillon.
Variables and Assignments
Key Points:
- Variables are abstractions within programs which represent a value
- Values can be individual data points or a list/collection that contains many data values
- Types of data: numbers, Booleans (T/F), lists, and strings
In Python
Defining a variable by setting it equal to the type of variable.
#defining all the variables using the equal sign
numbervariable = 25
stringvariable = "word"
numberlist = [1, 2, 3, 4, 5]
stringlist = ["a", "b", "c", "d", "e"]
israining = False
#printing all the defined variables
print(numbervariable)
print(stringvariable)
print(numberlist)
print(stringlist)
print(israining)
Variables can be modified through mathematical expressions, lists, dictionaries and more.
Variables can be interchanged through functions like this.
var1 = "word" # defining first variable
var2 = "number" # defining second variable
temp = var1 # defining temporary variable using the first variable
var1 = var2 # changing the first variable value as the second variable value
var2 = temp # changing the second variable value to the first variable value
var x = "See?"
const y = "This"
let z = "works!"
console.log(x, y, z)
Otherwise, it works pretty much the same in terms of mechanics. One difference has to do with how the scale of a variable is determined, but that isn't covered in the lesson.
Data Abstraction
Key Points:
- A list is made up of elements organized in a specific order
- An element is a unique, individual value in a list
- A string differs from a list as it is a sequence of characters rather than elements
- Data abstraction uses a list by taking specific data elements from a list and organizing into a whole, less complex representation of the values such as a table
- Remember that the indexes in AP materials start at 1 for some reason!
In Python
Data abstraction is most often done through dictionaries and lists. Below is a code cell provided by the teachers which shows multiple more functions of Python that are useful in terms of data abstraction (for example, id()
and using +=
to add ['cookies']
).
shopping_list = ["milk",
"pasta",
"eggs",
"spam",
"bread",
"rice"
] # list syntax is "[]"
another_list = shopping_list
print(id(shopping_list)) # each object has a uniques id; the id() function returns this id for the specifies object
print(id(another_list)) # As shopping_list is attritibuted to another_list, the id for both are the same as the object in questiom does not change
print(another_list)
shopping_list += ["cookies"] # adding cookies to the list
print(shopping_list)
print(id(shopping_list)) # the id does not change
print(another_list)
a = b = c = d = e = f = another_list # it is possibe to atrribute the same object to various variables
print(a)
print("Adding cream")
# .append() is a function which can be used to place new items into old lists
b.append("cream") # changes in one of the variables chnges all the lists in other as the object in question is the same.
print(a)
print(c)
print(d)
Properties stated within lists (or dictionaries) can be used to divide a list into more precise lists.
data = [
"Andromeda - Shrub",
"Bellflower - Flower",
"China Pink - Flower",
"Daffodil - Flower",
"Evening Primrose - Flower",
"French Marigold - Flower",
"Hydrangea - Shrub",
"Iris - Flower",
"Japanese Camellia - Shrub",
"Lavender - Shrub",
"Lilac - Shrub",
"Magnolia - Shrub",
"Peony - Shrub",
"Queen Anne's Lace - Flower",
"Red Hot Poker - Flower",
"Snapdragon - Flower",
"Sunflower - Flower",
"Tiger Lily - Flower",
"Witch Hazel - Shrub",
]
# two empty lists
flowers = []
shrubs = []
for plant in data: # A for loop that goes through each item in the list
if "Flower" in plant:
flowers.append(plant) # executed if "flowers" is in the item
elif "Flower" not in plant:
shrubs.append(plant) # executed if "shrubs" is in the item
print("Shrubs {}".format(shrubs)) # The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}
print("Flowers {}".format(flowers))
Individual elements inside lists can be abstracted through for loops.
albums = [("Welcome to my nightmare", "Alice cooper", 1975),
("Bad Company", "Bad Company", 1974),
("Nightflight", "Budgie", 1981),
("More Mayhem", "Emilda May", 2011),
("Ride the Lightning", "Metallica", 1984),
]
print(len(albums)) # number of items in the list
for name, artist, year in albums:
print("Album: {}, Artist: {}, year: {}"
.format(name, artist, year)) #returns a segregated and labled presentation of the songs
List elements can be split and joined through the split()
and join()
functions. Look at how the syntax works.
panagram = """the quick brown
fox jumps\tover
the lazy dog"""
words = panagram.split() # splitting the string above into individual words. Separator here is any whitespace.
print(words)
numbers = "9,223,372,036,854,775,807"
print(numbers.split(",")) # separator is ","
generated_list = ['9', ' ',
'2', '2', '3', ' ',
'3', '7', '2', ' ',
'0', '3', '6', ' ',
'8', '5', '4', ' ',
'7', '7', '5', ' ',
'8', '0', '7', ' ',
]
values = "".join(generated_list) # converting the list into a string
print(values)
values_list = values.split() # separator is any whitespace
print(values_list)
function Player(name, position, average) { // make a function
this.name = name; // different categories
this.position = position;
this.average = average;
this.role = "";
}
Player.prototype.setRole = function(role) { // whatever input we put into roles, it will be stored.
this.role = role;
}
Player.prototype.toJSON = function() {
const obj = {name: this.name, position: this.position, average: this.average, role: this.role};
const json = JSON.stringify(obj);
return json;
}
var manager = new Player("Bob Melvin", "Catcher", ".233"); // new player, including all the categories
console.log(manager);
console.log(manager.toJSON());
manager.setRole("Manager");
console.log(manager);
console.log(manager.toJSON());
And here, the function is used in a list to create many players.
var players = [ // make a list, storing all the categories we had in the previous code segment.
new Player("Manny Machado", "Third Base", ".299"),
new Player("Trent Grisham", "Center Field", ".185"),
new Player("Jake Cronenworth", "Second Base", ".238"),
new Player("Jurickson Profar", "Left Field", ".240"),
new Player("Ha-Seong Kim", "Shortstop", ".252"),
new Player("Brandon Drury", "First Base", ".226"),
new Player("Jorge Alfaro", "Catcher", ".249"),
new Player("Wil Myers", "Right Field, First Base", ".255"),
new Player("Juan Soto", "Right Field", ".242"),
new Player("Austin Nola", "Catcher", ".248"),
new Player("Josh Bell", "Designated Hitter, First Base", ".191"),
new Player("Jose Azocar", "Outfield", ".272"),
];
function Padres(manager, players){ // new function in order to store the data
manager.setRole("Manager");
this.manager = manager;
this.padres = [manager];
this.players = players;
this.players.forEach(player => { player.setRole("Player"); this.padres.push(player); });
this.json = [];
this.padres.forEach(player => this.json.push(player.toJSON()));
}
sd2022 = new Padres(manager, players); // this is how we will display it.
console.log(sd2022.padres);
console.log(sd2022.padres[0].name);
console.log(sd2022.json[0]);
console.log(JSON.parse(sd2022.json[0]));
And since this is written in JavaScript, we are fairly easily able to convert the data into JSON, and then into HTML.
Padres.prototype._toHtml = function() { // display data in a table
var style = (
"display:inline-block;" +
"border: 2px solid grey;" +
"box-shadow: 0.8em 0.4em 0.4em grey;"
);
// set up the table
var body = "";
body += "<tr>";
body += "<th><mark>" + "Name" + "</mark></th>";
body += "<th><mark>" + "Position" + "</mark></th>";
body += "<th><mark>" + "Batting Average" + "</mark></th>";
body += "<th><mark>" + "Role" + "</mark></th>";
body += "</tr>";
// include the data in the table according to categories.
for (var row of sd2022.padres) {
body += "<tr>";
body += "<td>" + row.name + "</td>";
body += "<td>" + row.position + "</td>";
body += "<td>" + row.average + "</td>";
body += "<td>" + row.role + "</td>";
body += "<tr>";
}
// html format
return (
"<div style='" + style + "'>" +
"<table>" +
body +
"</table>" +
"</div>"
);
};
$$.html(sd2022._toHtml());