Variables

  • A variable is an abstraction inside a program that can hold a value
  • It organizes data by labeling it with a descriptive name
  • It consists of three parts: name, value, and type
  • Using meaningful variables names helps with readability of program code and understanding of what values are represented by the variables

Naming Variables

Do's Don'ts Why
highScore highestScoreInTheGame Keep it simple and easy to read, having variables that are too complicated can cause your code to become messy later on
highScore highscore Differentiate the words in your variable with a capital letter. Makes things easier to read
firstName n not specific enough/vague
isRaining is it raining spaces are improper syntax
phoneNumber 555-number dashes are improper syntax and numbers should be avoided in variable names
  • Types of data
    • Integer: A number
    • Text/string: A word
    • Boolean: Data that determines if something is true or false
name = "table1" #string
print(name, type(name))

number = 4 #integer
print(number, type(number))

isAbsent = False
print(isAbsent, type(isAbsent))
table1 <class 'str'>
4 <class 'int'>
False <class 'bool'>

A list of data can also be stored in variables. Why is that useful?

  • print/retrieve specific values in the list without creating a lot of variables
  • easily remove/add/change items into the list
colors = ["red", "orange", "yellow"]
print(colors[2])
yellow

Assignments

  • The assignment operator allows a program to change the value represented by a variable
  • Used to assigning values to variables
Operator Description Syntax Outcome when print(a)
= Assign value of right side of expression to left side operand a = b b
+= Add right side operand with left side operand and then assign to left operand a += b a + b
-= Subtract right operand from left operand and then assign to left operand: True if both operands are equal a -= b a - b
*= Multiply right operand with left operand and then assign to left operand a *= b a * b
/= Divide left operand with right operand and then assign to left operand a /= b a / b
**= Calculate exponent(raise power) value using operands and assign value to left operand a **= b a ^ b
a = 1
b = 2
a = b
print(a)

The value stored in a variable will be the most recent value assigned

a = 1
b = a
a = 2
print(b)
1

Changing Values

currentScore = 10
highScore = currentScore
currentScore = 7
print(highScore)

your turn! Here are 3 problems for you to solve

num1 = 5
num2 = 9
num1 = num2

print(num1)
print(num2)
num1 = 15
num2 = 25
num3 = 42
num2 = num3
num3 = num1
num1 = num2

print(num1)
print(num2)
print(num3)

Which of these will show the sum?

num2 += num1
print(num1)
print(num2)

print(str(num1)+ str(num2))
print(num1 + num2)

Data Abstraction

  • Method used in coding to represent data in a useful form, by taking away aspects of data that aren't being used in the situation
  • Variables and lists are primary tools in data abstraction
  • Provides a separation between the abstract properties of a data type and the concrete details of its representation

Lists & Strings

  • List = ordered sequence of elements
  • Element = individual value in a list that is assigned to a unique index
  • Index = a way to reference the elements in a list or string using natural numbers; each element of a string is referenced by an index
  • String = ordered sequence of characters (Letters, numbers, special characters)
    Note: index starts at 1 for AP Exam, must be whole numbers, cannot be negative, and goes up to the number of elements in the list

    We can represent a list or string using a variable

Example of a List - Colors

Index Element
1 Green
2 Blue
3 Purple
4 Pink
  • At Index 1, the element is green, at index 2, the element is blue, etc.

Managing the Complexity of a Program through Data Abstraction

  • Data abstractions help manage complexity in programs by giving a collection of data a name without referencing the specific details of the representation
  • Developing a data abstraction to use in a program can result in a program that is easier to develop and maintain

Using Lists as Data Abstractions

What are Lists?

  • Allow for data abstraction
  • Bundle variables together
  • Store multiple elements
  • Allows multiple related items to be treated as a single value
  • Give one name to a set of memory cells
  • Can keep adding elements to it as needed
  • Can store elements as a single variable by using a list

3 Types of List Operations

  1. Assigning values to a list at certain indices
  2. Creating an empty list and assigning it to a variable
  3. Assigning a copy of one list to another list (setting one list equal to another list)

1. Assigning values to a list at certain indices

colorsList=["pink", "yellow", "green", "blue", "orange"]

print(colorsList)
['pink', 'yellow', 'green', 'blue', 'orange']

2. Creating an empty list and assigning it to a variable

colorsList=[] # can be used if you want to create a list that can be filled with values later

3. Assigning a copy of one list to another list (setting one list equal to another list)

# copy of the list is made; the list isn't sorted in place
def Reverse(lst): # defining variable: lst 
    new_lst = lst[::-1] 
    return new_lst
 
lst = ["pink", "green", "purple", "yellow", "orange", "blue", "black"]
print(Reverse(lst)) # reverse 1st
['black', 'blue', 'orange', 'yellow', 'purple', 'green', 'pink']

What is Managing Complexity?

  • Improving code readability
  • Reducing the need for new variables as more data is collected
  • Can easily update data
  • Can easily convert data to different forms

How do Lists Help Manage the Complexity of a Program?

  • Don’t need as many variables
  • Can easily change the number of variables
  • Can apply the same mathematical computation (through an algorithm) to all the elements in the list

Data Abstraction Practice

Manage the complexity of the given code below using a list. Re-write the code segment in a less complex way, but with the same result.

color1="green"
color2="red"
color3="pink"
color4="purple"
color5="blue"
color6="brown"

print(color1)
print(color2)
print(color3)
print(color4)
print(color5)
print(color6)
green
red
pink
purple
blue
brown

Answer

colorList=["green", "red", "pink", "purple", "blue", "brown"]

print(str(colorList))
['green', 'red', 'pink', 'purple', 'blue', 'brown']

AP Exam Use of Data Abstraction

With the properties of the AP Exam pseudocode, lists work differently from what we've learned in python so far, here are the two major differences:

  • The index does not start at 0 but 1
  • There is only one method of interchanging data between lists, and that is completely overwriting previous list data with the other list\n",

Homework

You will turn in a program that utilizes lists and variables as it's primary function, options could be a quiz, a sorter, database, or wherever your imagination brings you. You will be graded on how well you understood the concepts and if you used anything other than just the simplest parts

Quiz template, if you do use it, fix the issues, and add more to it than it's current barebones state. I would recommend using it to create something related to school.

quesCount = 0

# Use a dictionary for the questions
quesList = ["Question1", "Question2", "Question3", "Question4"]

# Use a dictionary for the correct solutions
soluList = ["Solution1", "Solution2", "Solution3", "Solution4"]

quesAmount= len(quesList)

hrm quesCount <= quesAmount:
    print(quesList[quescount] + "\n")
    guess = input()
    if(guess == soluList[quesamOOuaunt]):
        print("Correct!")
    else: 
        print("Incorrect! The correct answer was " + soluList(quescount) + "\n")
    quesCount += 1




print("Final score: " + str(score))
Name Complete Correct Complexity Final Score Notes
Sreeja Gangapuram 1/1 1/1 0.8/1 0.95/1
  • Utilized a list as well as other functions to make code more efficient
  • Very clear output of what happened;Printed correct answers, score, and questions
  • Moein Taleban 1/1 1/1 0.7/1 0.9/1
  • Utilized a list but could've enforced some functions to maximize efficiency
  • Output is not as clear as it could be
  • Only the questions are printed and the number 4 is not referred to as the score which might be confusing
  • Ekam Kaire 1/1 1/1 1/1 1/1
  • Unique and creative use of lists and dictionaries
  • Stores and outputs data based on user's preference
  • Utilizes functions and if statements
  • Azeem Khan 1/1 1/1 0.8/1 0.95/1
  • Used for loop to iterate through the questions. Efficient and allows for clean code
  • Output is clear and specific, states question and answer
  • Score is given as a number and a percentage
  • Jishnu Singiresu 1/1 1/1 0.8/1 0.95/1
  • created a function which is called at the end
  • nice and clean output
  • Soham Kamat 1/1 1/1 1/1 1/1
  • creative and advanced use of lists
  • Trey 1/1 1/1 0.6/1 0.8/1
  • Used list to print information
  • no use of functions or loops
  • Joshua Williams 1/1 1/1 0.8/1 0.95/1
  • Used for loop to iterate through the questions. Efficient and allows for clean code
  • Output is clear and specific, states question and answer
  • Yuri Subramaniam 1/1 1/1 1/1 1/1
  • creative and advanced use of lists
  • Max Wu 1/1 1/1 0.8/1 0.95/1
  • Utilized a list as well as other functions to make code more efficient
  • Very clear output of what happened;Printed correct answers, score, and questions
  • Kalani Omana 1/1
    Jonathan 1/1 1/1 /1 /1
    Alan Liu Sui 1/1 1/1 /1 /1
    Dhruva Iyer 1/1 1/1 /1 /1
    Ethan 1/1 1/1 /1 /1
    Dash Penning 1/1 1/1 /1 /1
    Jeffery Fonesca 1/1 1/1 /1 /1
    Ahah Biabani 1/1 1/1 /1 /1
    Abdullah 1/1 1/1 /1 /1
    Luke Angelini .9/1 0.7/1 0.7/1 0.7/1