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)
25
word
[1, 2, 3, 4, 5]
['a', 'b', 'c', 'd', 'e']
False

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

In JavaScript

Variables in JavaScript have a different syntax. You can use var, const or let before the desired variable name, then set it equal to the variable's value.

var x = "See?"
const y = "This"
let z = "works!"
console.log(x, y, z)
See? This works!

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)
4385360576
4385360576
['milk', 'pasta', 'eggs', 'spam', 'bread', 'rice']
['milk', 'pasta', 'eggs', 'spam', 'bread', 'rice', 'cookies']
4385360576
['milk', 'pasta', 'eggs', 'spam', 'bread', 'rice', 'cookies']
['milk', 'pasta', 'eggs', 'spam', 'bread', 'rice', 'cookies']
Adding cream
['milk', 'pasta', 'eggs', 'spam', 'bread', 'rice', 'cookies', 'cream']
['milk', 'pasta', 'eggs', 'spam', 'bread', 'rice', 'cookies', 'cream']
['milk', 'pasta', 'eggs', 'spam', 'bread', 'rice', 'cookies', 'cream']

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))
Shrubs ['Andromeda - Shrub', 'Hydrangea - Shrub', 'Japanese Camellia - Shrub', 'Lavender - Shrub', 'Lilac - Shrub', 'Magnolia - Shrub', 'Peony - Shrub', 'Witch Hazel - Shrub']
Flowers ['Bellflower - Flower', 'China Pink - Flower', 'Daffodil - Flower', 'Evening Primrose - Flower', 'French Marigold - Flower', 'Iris - Flower', "Queen Anne's Lace - Flower", 'Red Hot Poker - Flower', 'Snapdragon - Flower', 'Sunflower - Flower', 'Tiger Lily - Flower']

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
5
Album: Welcome to my nightmare, Artist: Alice cooper, year: 1975
Album: Bad Company, Artist: Bad Company, year: 1974
Album: Nightflight, Artist: Budgie, year: 1981
Album: More Mayhem, Artist: Emilda May, year: 2011
Album: Ride the Lightning, Artist: Metallica, year: 1984

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)
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
['9', '223', '372', '036', '854', '775', '807']
9 223 372 036 854 775 807 
['9', '223', '372', '036', '854', '775', '807']

In JavaScript

Here is a large example provided by the instructors to show JavaScript data abstraction.

Below sets up functions to create the new "Player" object.

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());
Player {
  name: 'Bob Melvin',
  position: 'Catcher',
  average: '.233',
  role: '' }
{"name":"Bob Melvin","position":"Catcher","average":".233","role":""}
Player {
  name: 'Bob Melvin',
  position: 'Catcher',
  average: '.233',
  role: 'Manager' }
{"name":"Bob Melvin","position":"Catcher","average":".233","role":"Manager"}

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]));
[ Player {
    name: 'Bob Melvin',
    position: 'Catcher',
    average: '.233',
    role: 'Manager' },
  Player {
    name: 'Manny Machado',
    position: 'Third Base',
    average: '.299',
    role: 'Player' },
  Player {
    name: 'Trent Grisham',
    position: 'Center Field',
    average: '.185',
    role: 'Player' },
  Player {
    name: 'Jake Cronenworth',
    position: 'Second Base',
    average: '.238',
    role: 'Player' },
  Player {
    name: 'Jurickson Profar',
    position: 'Left Field',
    average: '.240',
    role: 'Player' },
  Player {
    name: 'Ha-Seong Kim',
    position: 'Shortstop',
    average: '.252',
    role: 'Player' },
  Player {
    name: 'Brandon Drury',
    position: 'First Base',
    average: '.226',
    role: 'Player' },
  Player {
    name: 'Jorge Alfaro',
    position: 'Catcher',
    average: '.249',
    role: 'Player' },
  Player {
    name: 'Wil Myers',
    position: 'Right Field, First Base',
    average: '.255',
    role: 'Player' },
  Player {
    name: 'Juan Soto',
    position: 'Right Field',
    average: '.242',
    role: 'Player' },
  Player {
    name: 'Austin Nola',
    position: 'Catcher',
    average: '.248',
    role: 'Player' },
  Player {
    name: 'Josh Bell',
    position: 'Designated Hitter, First Base',
    average: '.191',
    role: 'Player' },
  Player {
    name: 'Jose Azocar',
    position: 'Outfield',
    average: '.272',
    role: 'Player' } ]
Bob Melvin
{"name":"Bob Melvin","position":"Catcher","average":".233","role":"Manager"}
{ name: 'Bob Melvin',
  position: 'Catcher',
  average: '.233',
  role: 'Manager' }

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());
</table></div> </div> </div> </div> </div> </div>

Independent Work

A couple of assignments were given by the instructors. There is a "Challenge" and "Homework/Hacks".

Challenge

We were asked to use the defined maximum and minimum values to print out the index value and actual value of every number that does not fit within those bounds.

data = [104, 101, 4, 105, 308, 103, 5, 107,
    100, 306, 106, 102, 108]    # list of the different numerical values
min_valid = 100  # minimum value
max_valid = 200  # maximum value

def condition_check(i):
    global min_valid
    global max_valid
    global data
    if i < len(data):
        if (min_valid <= data[i] <= max_valid):
            condition_check(i + 1)
        else:
            print("At index value " + str(i) + ", the number", str(data[i]), "does not satisfy the conditions.")
            condition_check(i + 1)

condition_check(0)
At index value 2, the number 4 does not satisfy the conditions.
At index value 4, the number 308 does not satisfy the conditions.
At index value 6, the number 5 does not satisfy the conditions.
At index value 9, the number 306 does not satisfy the conditions.

Homework/Hacks

Here is the album input program they wanted us to make.

albums = [
    ("Welcome to my Nightmare", "Alice Cooper", 1975,   # First album list
     [
         (1, "Welcome to my Nightmare"),
         (2, "Devil's Food"),
         (3, "The Black Widow"),
         (4, "Some Folks"),
         (5, "Only Women Bleed"),
     ]
    ),
    ("Bad Company", "Bad Company", 1974,   # Second album list
     [
         (1, "Can't Get Enough"),
         (2, "Rock Steady"),
         (3, "Ready for Love"),
         (4, "Don't Let Me Down"),
         (5, "Bad Company"),
         (6, "The Way I Choose"),
         (7, "Movin' On"),
         (8, "Seagull"),
     ]
    ),
    ("Nightflight", "Budgie", 1981,
     [
         (1, "I Turned to Stone"),
         (2, "Keeping a Rendezvous"),
         (3, "Reaper of the Glory"),
         (4, "She Used Me Up"),
     ]
     ),
    ("More Mayhem", "Imelda May", 2011,
     [
         (1, "Pulling the Rug"),
         (2, "Psycho"),
         (3, "Mayhem"),
         (4, "Kentish Town Waltz"),
     ]
     ),
]

i = 0
#below used to collect a temporary input value, with a built-in invalid input handling system
def get_input():
    global i #i is always redefined to equal the length of the list that rsp is in reference to
    rsp = input()
    try:
        if (0 < int(rsp) <= i): #ensures the response is in a valid range
            returnval = int(rsp)
            return(returnval)
        else:
            print("Invalid response.")
            return "Error"
    except: #error handler if a non-integer is input
        print("Invalid response.")
        return "Error"

print("Which album would you like to listen to?") #initial query
for album, artist, year, songs in albums: #separating all parts of the data
    i += 1
    print(str(i) + '. "' + album + '" (' + str(year) + ") by " + artist)
choice = get_input()
if choice == "Error": #ends the process if an error has occurred
    pass
else:
    chosenalbum = albums[int(choice) - 1][0] #redefining different parts of the list for clarity
    chosenartist = albums[int(choice) - 1][1] #(this wouldn't be necessary if it was a dictionary)
    chosenyear = albums[int(choice) - 1][2]
    chosensongs = albums[int(choice) - 1][3]
    i = len(chosensongs)
    print('You chose "' + chosenalbum + '" (' + str(chosenyear) + ") by " + chosenartist + ".")
    print("Which song would you like to listen to?")
    for number, song in chosensongs:
        print(str(number) + ". " + song)
    choice2 = get_input()
    if choice2 == "Error": #ends the process if an error has occurred
        pass
    else:
        for number, song in chosensongs:
            if int(choice2) == number:
                print('Playing "' + song + '"...')
                pass
Which album would you like to listen to?
1. "Welcome to my Nightmare" (1975) by Alice Cooper
2. "Bad Company" (1974) by Bad Company
3. "Nightflight" (1981) by Budgie
4. "More Mayhem" (2011) by Imelda May
You chose "Bad Company" (1974) by Bad Company.
Which song would you like to listen to?
1. Can't Get Enough
2. Rock Steady
3. Ready for Love
4. Don't Let Me Down
5. Bad Company
6. The Way I Choose
7. Movin' On
8. Seagull
Playing "Movin' On"...
</div>
Name Position Batting Average Role
Bob Melvin Catcher .233 Manager
Manny Machado Third Base .299 Player
Trent Grisham Center Field .185 Player
Jake Cronenworth Second Base .238 Player
Jurickson Profar Left Field .240 Player
Ha-Seong Kim Shortstop .252 Player
Brandon Drury First Base .226 Player
Jorge Alfaro Catcher .249 Player
Wil Myers Right Field, First Base .255 Player
Juan Soto Right Field .242 Player
Austin Nola Catcher .248 Player
Josh Bell Designated Hitter, First Base .191 Player
Jose Azocar Outfield .272 Player