Unit 3.1-3.2 Class Jupyter Notebook Period 4
Jupyter Notebook for the rest of the class to follow along with.
- Unit 3, Section 1.1: Data Types and Variables - Ederick
- Hacks
- Variables (3.1.2) - Noor
- My Answer to Hacks:
- List and Strings Using Variables- Nathan
- Hacks 3 My Answers
- Data Abstraction with Lists - Steven
- Data abstraction can be created with lists.
- In the code below, the logic itself works with a list, but the code abstracts it into a sequence of bits in a string (as seen in the input and output). To make this work, the splitbits lists is created and processed. At the end of the code, the result is outputted as a string rather than a list (abstraction).
- Hacks
- Managing Complexity with lists - Liav
Unit 3, Section 1.1: Data Types and Variables - Ederick
Essential Knowledge (College Board's Must Knows):
- A variable is an abstraction inside a program that holds a value, where each variable has associated data storage that represents a single value at a time (However, if the value is a collection type such as a list, then the value can contain multiple values).
- Variables typically have meaningful names that helps with the overall organization of the code and understanding of what is being represented by the variables
- Some programming languages provide a variety of methods to represent data, which are referenced using variables 9Booleans, numbers, lists, and strings)
- One form of a value is better suited for representation than antoher.
What is a Variable?
A variable is an abstraction made inside a program that holds a value. These variables are used in code to refer to more comples values that the variable contains and makes the program code more organized and smoother to run.
Variables can be seen as "containers" and each container has a name that holds what it is supposed to hold. In the following code, we can see that a variable has the value of "Alex." How can we make the variable appear more organized in the code?
x = "alex"
print(x)
Choosing Variables
When choosing variables, it is important to assign the variables name to something that correlates with what the function of the variable is supposed to do. For example, we do not want a variable that is supposed to hold a name be named "age" becaue it can be confusing and mistakes may be more prevalent.
Example:
age = "Timmy"
name = "25"
print(name + " is " + age)
- Notice how age is going to be seen when printing the code. That can lead to confusion
Data Types
Variables have different data types that store specific kinds of data depending on what is being represented. Some examples are shown below:
- integer (numbers)
- string (or text/letters)
- Boolean (True/False statements)
These types of data types can be useful when trying to represent a value. For example, you would not want a variable meant to represent someone's name with an integer.
Questions (College Board's Essential Knowledge):
- What exactly IS a variable?
- What is the best data type to represent someone's dog's name?
- Why is it important to give variables specific names before containing values?
- What is the best way to represent someone's phone number?
Bonus (Not required but important to know):
- How can we update a variable's value
- What function is used to recieve a user's input?
age = 15 #integer
favorite_color = "pink" #string
alive = True #boolean
print("This person is " + str(age) + " and their favorite color is " + favorite_color)
#having the variables named like this make the variables usable and easily identifiable
if alive == True:
print ("This person is alive")
else:
print ("This person has passed away")
Learning objective for 3.1.2:
Determine the value of a variable as a result of an assignment
- done through looking at how we can use the assignment operator
Note:
Collegeboard uses <-- as the assignment operator
- The assignment operator looks different for different types of coding languages A variable will take the most recent value assigned
How do you even store a value inside a variable?
Let's use python for our example:
- In python, the assignment operator is the equal sign (=)
- In order to store a value inside a variable, we must:
- Give the variable a name
- place the assignment operator
- input the variable value
highscore = 100
# How do you store a number like 3.72?
money = 3.72
# What about storing your username (string)?
username = "name"
# What if it is raining outside and you want to store that fact (boolean)?
is_raining = True
# What about a list of groceries?
groceries = ["eggs", "flour", "bread", "milk"]
x = 10
y = 20
z = 30
x = y
z = x
# what do you think z will be?
print(z)
Let's get a little more practical here
Imagine that you are making a calendar and have just finished the html code that is needed:
- You now want to be able to switch between the months of the year by using the "next" or "prev" buttons
- you will need to take the html elements and use them to your advantage
- but how?
- you will need to take the html elements and use them to your advantage
<body>
<div class="container">
<div class="calendar">
<div class="month">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
</div>
</div>
<script>
// to make our lives a little easier, we can store the div next and prev into variables
// this way we don't need to type out as much
// Note: You CAN just add the event listener to document.querySelector(.next) or prev and get the same desired outcome
nextButton = document.querySelector(.next)
prevButton = document.querySelector(.prev)
// we can go make the buttons functional by adding an addeventlistner to them
</script>
Recap:
- We learned what is a assignment operator
- We learned how to use the assignment operator
- We learned how to store a value inside a variable using the assignment operator
- We experimented with a few examples
Hacks:
Answer these:
- In your own words, briefly explain by writing down what an assignment operator is
- In Collegeboard pseudocode, what symbol is used to assign values to variables?
- A variable, x, is initially given a value of 15. Later on, the value for x is changed to 22. If you print x, would the command display 15 or 22?
Hacks:
Copy the all the html code into a markdown file and run your local server. You will then see a decimal to binary converter near the html code. The problem is that it is not converting the decimal to binary. This is because the variables are not defined properly and it is your job to use the information learned today to fix the converter. Don't change the css
Bonus (optional):
There's more than one way to define the variable. List two ways to do it.
My Answer to Hacks:
-
An assignment operator, like the "=" in python, assigns a value to a variable. Assignment operators can assign strings, integers, and booleans to variables. This allows for a user to use the variables in various functions.
-
In Colledgeboard pseudocode, the symbol "<--" is the assignment operator (assigns values to variables).
-
The print command will print the latest value of a variable. Due to the value of x being changed to 22, the command will display 22, not 15.
List and Strings Using Variables- Nathan
Strings
Strings is a series of characters (numbers, letters, etc), one example of a string is your name or your id because strings can contain both numbers and letters.
The following are all examples of strings being used in code, in this case, within print functions.
print("hello world")
print('hello')
thanksgivingList = ["cranberry pie", "casserole", "mashed potatoes", "turkey"]
print(thanksgivingList)
print(thanksgivingList[1]) #In this case, the index starts at 0, but in collegeboard, the index starts at 1
print(thanksgivingList[-3]) #Python can index from the end, in this case, "turkey" would be index -1 and 3.
Hacks
Questions
- What is a list?
- What is an element
- What is an easy way to reference the elements in a list or string?
- What is an example of a string?
Hacks
- Create a list with indices
- Index a part of the list that you created.
- Try to index from the end
Create an index of your favorite foods
Tips: Index starts at 1, Strings are ordered sequences of characters
Extra work: Try to create an index that lists your favorite food and print the element at index 3. More work: Create a list of your favorite foods and create an index to access them.
marks = ["food1"]
Rubric
Creating a list
- Shows great knowledge in creating lists
Indexing
- Is able to index both from the start and from the end
favfoods = ["mac and cheese", "pizza", "pasta", "Goldfish"] #normal list
print(favfoods[3]) #this prints the fourth element (index 3) because in python the index starts at 0
print(favfoods[-1]) #This prints the fourth element as well
#below is a dictionary of lists to show my understanding
awesomefoods = {
"Pastas" : ["bowtie", "penne", "macaroni"],
"Deserts" : ["ice cream", "cake", "cupcakes", "milkshake", "brownies", "pie"],
"Drinks" : ["Fanta", "Shirley Temple", "Sprite", "Coke", "Pepsi"]
}
#indexing the elements within the lists within the dictionary
print(awesomefoods["Pastas"]) #This will print all the pastas in the pasta list
print(awesomefoods["Deserts"][3]) #This will print out the fourth element in the deserts list
print(awesomefoods["Drinks"][-2]) #This will print the fourth element in the drinks list
Data Abstraction with Lists - Steven
Data abstraction can be created with lists.
- Lists bundle together multiple elements and/or variables under one name are not defined with specified lengths.
- The variables that are stored in a list do not have to be limited to one kind of variable.
- The user does not need to know how the list stores data (this gives way for data abstraction).
In the code below, the logic itself works with a list, but the code abstracts it into a sequence of bits in a string (as seen in the input and output). To make this work, the splitbits lists is created and processed. At the end of the code, the result is outputted as a string rather than a list (abstraction).
bits = input("Input a sequence of bits to invert: ")
splitbits = list(bits)
for i in range(len(splitbits)):
if splitbits[i] == '0':
splitbits[i] = '1'
elif splitbits[i] == '1':
splitbits[i] = '0'
print("".join(splitbits))
num1=input("Input a number. ")
num2=input("Input a number. ")
num3=input("Input a number. ")
add=input("How much would you like to add? ")
# Add code in the space below
numlist = [int(num1), int(num2), int(num3)]
# The following is the code that adds the inputted addend to the other numbers. It is hidden from the user.
for i in numlist:
numlist[i -1] += int(add)
print(numlist)
score1 = 95
score2 = 24
score3 = 87
score4 = 92
print(score1, score2, score3, score4)
- As you can see, each score is assigned to its relative variable such as "score1 = 95" and then you just print each variable.
- However you can make the code segment faster, easier to read, and more efficient...
scores = [95, 24, 87, 92]
print(scores)
- Now instead of having a difference variable and new line of code for each value, the list is simply displayed by assigning each value to a single value that you can now print.
How lists manage complexity of a program
-
Simplification
- It is much simpler, faster, and easier to code lists this way
- Makes the code segment much easier to read
-
Variables
- You do not need as many variables, because you can just assign all corresponding values to a single variable
- To change a value you don't have to edit/add/remove an entire variable
import getpass, sys
def question_with_response(prompt):
print("Question: " + prompt)
msg = input()
return msg
questions = 4
correct = 0
print('Hello, ' + getpass.getuser() + " running " + sys.executable)
print("You will be asked " + str(questions) + " questions.")
question_with_response("Are you ready to take a test?")
rsp = question_with_response("The purpose of lists and dictionaries are to manage the ____ of a program")
if rsp == "complexity":
print(rsp + " is correct!")
correct += 1
else:
print(rsp + " is incorrect!")
rsp = question_with_response("Lists are a form of data ______")
if rsp == "abstraction":
print(rsp + " is correct!")
correct += 1
else:
print(rsp + " is incorrect!")
rsp = question_with_response("Which brackets are used to assign values to a variable to make a list?")
if rsp == "[]":
print(rsp + " is correct!")
correct += 1
else:
print(rsp + " is incorrect!")
print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions))
food1 = "pizza"
food2 = "hot dog"
food3 = "sushi"
food4 = "strawberry"
food5 = "sandwich"
print(food1, food2, food3, food4, food5)
foods = ["pizza", "hot dog", "sushi", "strawberry", "sandwich"]
print(foods)
friend1 = "Alexa"
friend2 = "Lydia"
friend3 = "Jessica"
friend4 = "Nicole"
print(friend1, friend2, friend3, friend4)
# below is a list of my friends with managed complexity
friends = ["Alexa", "Lydia", "Jessica", "Nicole"]
print(friends)
Hacks
- On a single markdown file:
- Insert a screenshot of your score on the python quiz
- Insert a screenshot of your simplifying of the food list
- Why are using lists better for a program, rather than writing out each line of code?
- Make your own list the "long and slow way" then manage the complexity of the list
Rubric
- In ordere to earn a .20/.20 you must
- On a markdown post:
- make an attempt at the python quiz
- Successfully simplify the food list
- Answer the question in detail
- Provide evidence of your own list that you coded