Unit 3 Vocabulary

  • variables: "containers" or used to store information to be referenced and manipulated in a computer program
  • data types: a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it
  • assignment operators: the operator used to assign a new value to a variable
  • lists: an abstract data type that represents a finite number of ordered values
  • dictionaries: an abstract data type that defines an unordered collection of data as a set of key-value pairs
  • class: a template definition of a method and variable in a particular kind of object
  • algorithm: a procedure used for solving a problem or performing a computation
  • sequence: the order of how to do something to achieve a result
  • selection: allows an algorithm to make a decision based on if a condition is met
  • iteration: iteration: a loop and doing something again until a condition is met
  • expressions: a concept in which a number of variables or constants, and operators and functions, are put together in a single statement that is acted on by a particular programming language
  • comparison operators: compare the values within an expression, such as to check if the value held by a variable matches the value held by another variable
  • boolean expression: a logical statement that is either TRUE or FALSE
  • truth tables: a breakdown of all the possible truth values returned by a logical expression (usually 1/0, true/false)
  • characters: a display unit of information equivalent to one alphabetic letter or symbol
  • strings: an array data structure of bytes (or words) that stores a sequence of elements
  • length: length() function returns the number of items in an object
  • concatenation: the operation of joining two strings together
  • python if: a conditional statement tha decides if a certian condition is true/decides whether certain statements need to be executed or not
  • python elif: elif = else if and checks for multiple expressions (if the condition for if is False, it checks the condition of the next elif block)
  • python else conditionals: else catches anything which isn't caught by the previous conditions (like and if statement)
  • nested selection statements: when more than one decision must be made before carrying out a task
  • Python for loop: a control flow statement that is used to repeatedly execute a group of statements as long as the condition is satisfied
  • Python while loop with range and with list: sets aside a block of code that is to be executed repeatedly until a condition is falsified
  • Combining loops with conditionals to Break, Continue:
  • Procedural Abstraction: when we create code sections which are generalised by having variable parameters (more simple)
  • Python Def procedures:
  • paramerters: a special kind of variable used in a function to refer to one of the pieces of data provided as input to the function
  • return values: a value that a function returns to the calling function when it completes its task

Below are examples of some vocab:

  • variables, data types, assignment operators, dictionaries, algorithm, sequence, selection, expressions, comparision operators, boolena expressions, strings, python if, else, for loop, list, iteration, procedural abstraction, combining loops with conditional to break
# algorithim example:
miles_of_gas = 30

while miles_of_gas >= 5:
    school = input("Would you like to go to school?")
    if school == "yes":
        print("You have gone to school")
        miles_of_gas -= 5
        print("You now have ", miles_of_gas, " miles of gas left")
    else:
        print("You have ", miles_of_gas, " miles of gas left")
        miles_of_gas = 0




# definitions
isalexatired = True #these are variables with the assignment operator "="
havehw = True
if isalexatired == True and havehw == False: # these are Booleans and comparison operators
    print("Stay home and sleep!")
else:
    if havehw == True: # more examples of nested conditionals
        print("Go to school")
    else:
        print("Stay home and sleep!")




# definitions
input_string = input("Input a string to check how many vowels it has. ") # another variable with the data type of string
vowelcount = 0 # assigning a number data type to a variable
for character in input_string: #iterates through the string character by character
    if character == "a":
        vowelcount += 1
    elif character == "e": # an example of an elif statement
        vowelcount += 1
    elif character == "i":
        vowelcount += 1
    elif character == "o":
        vowelcount += 1
    elif character == "u":
        vowelcount += 1
print(vowelcount)




# here is an example of a list that uses a for loop (iteration)
numlist = [50]
for i in numlist:
    i -= 1
    numlist.append(i) # .append is an example of procedural abstraction
    if i == 0:
        break # conditional to break the loop
print(numlist)

Lesson 3- 3.5-3.6

Booleans, relational operators, logical operators, conditionals, truth tables, nested conditionals

3.5

  • boolean= algebraic notation used to represent logical propositions; true or false
    • ex. testing if two numbers are equal (the sky is blue = True)
    • binary: true= 1, false= 0
  • relational operators= mathematical relationship between two variables and determines if statement is true
    • a=b, a>b...
  • logical operators= NOT, AND, OR
    • NOT= displays opposite of whatever data is, mainly true/false
      • ex. this = False
    • AND= evalutes two conditions together and determines if both conditions are met
      • ex. if > and <
    • OR= only looks to see if one condition is met
      • if _ < __ or_>_

Hacks 1

The logical operators:

  1. NOT: Not is a logical operator that reverses, or takes the opposite, of the data. For example, true would be false, and 1 would be 0.
  2. AND: decides if both conditions are met- usually an "if" statement and an action or decision will occur if both conditions are met. For example, if an animal is agressive AND hungry, then the animal will attack for food.
  3. OR: only one of two conditions needs to be met in order for OR to work. If one condition is met then an action or decision will occur. For example, if a person is old OR disabled, they may need a wheelchair.
print("NOT:")
computer_power = True # the computer is on
power_status = not(computer_power) # the opposite of one is off
print(power_status) # the computer is off

# This example below uses both AND and OR so you can see the different situations in which one would use them:
print("AND + OR:")
i = input("input a number between 1 and 10")
if int(i) > 10 or int(i) < 1: # i must satisfy one condition
    print("Your number is not in the range")
if int(i) >= 1 and int(i) <= 10: # i must satisfy both conditions
        print("Your number is in the range")
NOT:
False
AND + OR:
Your number is in the range

Conditionals

  • conditionals= allow for the expression of algorithims that utilize selection without a programming language
    • selection- block of code that will execute depending on the algorithim condition returning true or false
    • algorithim- a finite set of instructions that accomplish a specific task
    • conditional statement(If statement)- a statement that affects the sequence of control by executing certain statements depending on boolean value (true/false)

Hacks 2

Challenges:

userinput = input("Type in a string and see how many vowels are in it!")
vowelcount = 0
for i in userinput: #this will iterate through each character in the string 
    if i == "a": #if the character has an a, it will add one
        vowelcount = vowelcount + 1
    if i == "e": # if the character has an e, it will add one to the vowel count
        vowelcount = vowelcount + 1
    if i == "i": # if the character is an i, adds one
        vowelcount = vowelcount + 1
    if i == "o": # if the character is an o, adds one
        vowelcount = vowelcount + 1
    if i == "u": # if the character is a u, adds one
        vowelcount = vowelcount + 1
print("There are " + str(vowelcount) + " vowels in this string")
There are 5 vowels in this string
usernumber = input("please input a number")
multiples_sum = 0

if int(usernumber) >= 0: # this will make sure the input is positive
    for i in range(int(usernumber)+1): # this will iterate through each number up to the input
        if int(i) % 3 == 0: # I used MOD to figure out if the number is a multiple of 3 or 5
            multiples_sum += int(i) # this adds the multiple to the count and prints if the number is a multiple
            print(str(i) + " is a multiple of 3" ) 
        elif int(i) % 5 == 0: # same as above but for 5
            multiples_sum += int(i)
            print(str(i) + " is a multiple of 5")

print("The sum of the multiples of 3 and 5 for your input is = " + str(multiples_sum))
0 is a multiple of 3
3 is a multiple of 3
5 is a multiple of 5
6 is a multiple of 3
9 is a multiple of 3
10 is a multiple of 5
12 is a multiple of 3
The sum of the multiples of 3 and 5 for your input is = 45

Defining the key terms:

  • selection = a segment of code will only run if a specific condition is met example: selection image

  • algorithim = a function/code that completes a task or solves a problem. example: algorithim image

  • conditional statement = A statement or order of code that will occur if a specific condition is met (true/false) example:

    conditional statement image

usersinput = int(input("What was your percentage grade on the test?"))

if usersinput >= 75:
    print("Congradulations! You passed your test")
    if usersinput >= 90:
            print("You got an A!")
else:
    print("Im sorry, you failed. Try again next time!")
Congradulations! You passed your test

Nested Conditionals

  • Nested conditional statements- consist of conditional statements within conditional statements (one inside the other)
  • can have three different conditions

Hacks 3

Flow chart one: image in review ticket

people = int(input("How many people are you feeding for dinner?"))

if people >= 4:
    adults = int(input("How many adults are eating?"))
    children = int(input("How many children are eating?"))
    if adults > children:
        print("triple cooking porportions")
    else:
        print("souble cooking porportions")
else:
    print("Stick to normal cooking instructions")
triple cooking porportions

Flow chart two: image in review ticket

showering = input("Are you showering in the morning?")

if showering == "yes":
    drying_hair = input("Are you blow drying your hair?")
    if drying_hair == "yes":
        print("wake up at 6:30 AM to get ready")
    else:
        print("wake up at 6:45 AM to get ready")
else:
    print("wake up at 7:25 AM to get ready")
wake up at 7:25 AM to get ready

Flow chart three: image in review ticket

coffee = input("Do you like coffee?")

if coffee == "yes":
    espresso = int(input("How many shots of espresso do you want?"))
    if espresso <=1:
        print("Order a machiatto")
    else:
        print("get a double shot latte")
else:
    print("Order a tea")
get a double shot latte
congestion = input("Do you have a runny nose?")

if congestion == "yes":
    fever = input("Do you have a fever?")
    if fever == "yes":
        print("You have the flu :(")
    else:
        print("You have a cold:(")

else:
    pinkeye = input("Are your eyes red?")
    if pinkeye == "yes":
        print("You have pinkeye :(")
    else:
        print("You seem to be healthy!")
You have a cold:(
STEM = input("Do you like math and science?")

if STEM == "yes": # asks about math vs science and gives reccomendation
    math = input("Do you like math?")
    if math == "yes":
        print("You should take AP Calculus AB")
    else:
        print("You should take AP Biology")
else: # asks about non-STEM classes and gives reccomendation
    ceramics = input("Do you like working with clay?")
    if ceramics == "yes":
        print("You should take cermaics")
    else:
        print("You should take drawing and painting or photography")
You should take drawing and painting or photography

Lesson 4 3.8-3.10

  • Iteration: a repeating portion of an algorithm, repeats a specified number of times or until a given condition is met
  • Iteration Statements: change the sequential flow of control by repeating a set of statements zero or more times, until a stopping condition is met
  • Repeat Until: if the condition evaluates to true initially, the loop body is not executed at all, due to the condition being checked before the loop
  • can use i (define a variable) to represent the range of a value (string or integer) for loops
  • range function- goes through a value and can be used to have a starting value, ending value, and increment value (ex. range(1,11,2)); ending value is not included so may need to add one to get desired value

Logic example provided: image

Hacks 3.8.1

  1. Iteration is a term used in computer science to simplify code by repetition. The code will use loops to repeat until a condition is met.
  2. Iteration logic example: packing boxes
    1. grab a box
    2. add two blankets
    3. add one sleep mask
    4. repeat steps one, two, and three until you have 10 packed boxes
    5. pack the boxes into the truck
  3. below:
donuts = int(input("How many donuts do you have?"))

while donuts > 0:
    print("A student recieves a donut")
    donuts -= 1

print ("You have no donuts left")
A student recieves a donut
A student recieves a donut
A student recieves a donut
A student recieves a donut
A student recieves a donut
You have no donuts left

3.8.2

  • Iteration Statement - cause statements to be executed zero or more times, subject to some loop-termination criteria
  • range function = lists all integers leading up to the given number (but doesn't inlclude)

Hacks 3.8.2

  1. An iteration statement is a statement that executes a segment of code zero or more times in order until a condition is met or there is a break in the code.
decending_list = [int(input("What number would you like to countdown from?"))]  

for i in decending_list:
    i -= 1
    decending_list.append(i)
    if i == 0:
        break
print(decending_list)
    
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
i = 3

while i <= 81:
    print(i)
    i += 13 
3
16
29
42
55
68
81

3.8.3

  1. append() - adding element to the end of the list
  2. insert() - adding an element in a specific position
  3. remove() - remove an item from the list
  4. sort() - changes order of list permanently
  5. sorted() - returns a copy of the list which leaves the original copy unchanged
  6. range() - use to work with number efficiently
  7. min() - find the least value in list
  8. max() - find the highest value in list
  9. sum() - sum of all in list
  10. length() - returns the number of elements currently in a specified list

3.10.2

  • Traversing a list = is the process of visiting each element in a list in a sequential order. It can be used to access, search for, and modify elements in the list.

1) Complete Traversal: All elements in a list are assessed

2) Partial Traversal: Only a given portion of elements are assessed

3) Iterative Traversal: When loops are used to iterate through a list and to access each single element at a time.

Hacks Unit 3 Section 10

Quiz:

Quiz score image here (titled lessonfourquiz)

Minimum list:

  • Use the list made bellow
  • Make a variable to hold the minimum and set it to potential minimum value
  • Loop
  • Check each element to see if it is less than the minimum variable
  • If the element is less than the minimum variable, update the minimum
  • After all the elements of the list have been checked, display the minimum value
nums = ["10", "15", "20", "25", "30", "35"]

minimum = 50

for i in nums:
    if int(i) < minimum:
        minimum = int(i)

print (minimum)
10
monthly_earnings = []

a = 0
while a == 0: # this will continue asking for each month's earnings to add to the list until the user enters nothing (clicks enter)
    money = input("How much money did you make this month?")
    if money == "":
        break 
    monthly_earnings.append(int(money)) # this adds all of the input into the list
   
    

sort = input("Do you want to sort your earnings?") 

if sort == "yes": # if they want to sort earnings
    print("sorted:")
    print(sorted(monthly_earnings))
else: # if they don't want to sort earnings, it will print unsorted
    print("unsorted:")
    print(monthly_earnings)

print("Your highest monthly earning is $" + str(max(monthly_earnings)))
print("You have been working for " + str(len(monthly_earnings)) + " months")
sorted:
[2, 2, 5, 10, 1000]
Your highest monthly earning is $1000
You have been working for 5 months

3.9 and 3.11

3.9

  • However, Algorithms that look similar might not always have the same result
  • Different algorithms can be used to solve the same problem

Example: The function below would perform very differently but look similar if there were no equal sign after the 70:

print("What Grade Did You Get?")
grade = int(input("Enter Grade:"))
if grade >= 90:
        print("Wow! Good job!")
if 70 <= grade < 90:
        print("Nice!")
elif grade < 70:
        print("Do Better")
What Grade Did You Get?
Nice!

Hacks

3.9.1 Completion:

  1. It is important to know that algorithims that look different can do the same thing and that algorithims that look the same might have different results because users must look and examine algorithims carefully to predict the outcomes of algorithims. There is more than one way to create certain algorithims or algorithims may look the same and a person must be carefull not to make any assumptions.

  2. conditional to boolean below:

sweaty = True
dirty = False

if sweaty == True:
    print("Take a shower!")

else:
    if dirty == True:
        print("Take a shower!")
    
    else: 
        print("No need to take a shower. You're clean!")


# second way!

showering = dirty or sweaty 
if showering == True:
    print("Take a shower!")
if showering == False:
    print("No need to take a shower. You're clean!")
Take a shower!
Take a shower!

3.9.2 Hacks:

Completiom:

Flowchart

Linked in review ticket

Natural Language:

  1. Start
  2. The number of miles left of gas is 30 miles.
  3. Ask if you would like to go to school.
  4. Do you have 5 or more miles of gas?
  5. Every trip to school is 5 miles. You go to school and lose 5 miles.
  6. How many miles of gas are left?
  7. Decide if you would like to go to school again.
  8. Repeat steps 3-6 until you are out of gas or you don't want to go to school again.
  9. State gas level.
  10. End
miles_of_gas = 30

while miles_of_gas >= 5:
    school = input("Would you like to go to school?")
    if school == "yes":
        print("You have gone to school")
        miles_of_gas -= 5
        print("You now have ", miles_of_gas, " miles of gas left")
    else:
        print("You have ", miles_of_gas, " miles of gas left")
        miles_of_gas = 0
You have gone to school
You now have  25  miles of gas left
You have  25  miles of gas left
  • when working with others, MAKE NOTES IN CODE
  • there are many ways to do things
  • use flowcharts and natural code when planning algorithims
  • existing algorithims can help you write more complicated ones

3.9.3 Hacks

  • Flowchart linked in review ticket
import random

#sets variables for the game
num_guesses = 0
user_guess = -1
upper_bound = 100
lower_bound = 0

#generates a random number
number = random.randint(0,100)

# print(number)     #for testing purposes

print(f"I'm thinking of a number between 0 and 100.")

#Write a function that gets a guess from the user using input()
def guess():
    userguess = input("Choose a number!")
    return userguess

#Change the print statements to give feedback on whether the player guessed too high or too low
def search(number, guess):
    global lower_bound, upper_bound
    if int(guess) < int(number):
        print("Your guess is too high") 
        lower_bound = guess
        return lower_bound, upper_bound
    elif int(guess) > int(number):
        print("Your guess is too low")
        upper_bound = guess
        return lower_bound, upper_bound
    else:
        upper_bound, lower_bound = guess, guess
        return lower_bound, upper_bound 

while user_guess != number:
    user_guess = guess()
    num_guesses += 1
    print(f"You guessed {user_guess}.")
    lower_bound, upper_bound = search(number, user_guess)
    if int(upper_bound) == int(number):
        break
    else:
        print(f"Guess a number between {lower_bound} and {upper_bound}.")

print(f"You guessed the number in {num_guesses} guesses!")
I'm thinking of a number between 0 and 100.
You guessed 7.
Your guess is too high
Guess a number between 7 and 100.
You guessed 8.
Your guess is too high
Guess a number between 8 and 100.
You guessed 2.
Your guess is too high
Guess a number between 2 and 100.
You guessed 2.
Your guess is too high
Guess a number between 2 and 100.
You guessed 2.
Your guess is too high
Guess a number between 2 and 100.
You guessed .
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb Cell 41 in <cell line: 36>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=37'>38</a> num_guesses += 1
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=38'>39</a> print(f"You guessed {user_guess}.")
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=39'>40</a> lower_bound, upper_bound = search(number, user_guess)
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=40'>41</a> if int(upper_bound) == int(number):
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=41'>42</a>     break

/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb Cell 41 in search(number, guess)
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=21'>22</a> def search(number, guess):
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=22'>23</a>     global lower_bound, upper_bound
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=23'>24</a>     if int(guess) < int(number):
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=24'>25</a>         print("Your guess is too high") 
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/avac54765/vscode/fastpages-ava/_notebooks/2022-12-04-Livereviewtwo.ipynb#X62sdnNjb2RlLXJlbW90ZQ%3D%3D?line=25'>26</a>         lower_bound = guess

ValueError: invalid literal for int() with base 10: ''

3.11

  • binary trees- find the center by sorting a list and indexing the center
    • place the middle element in the center and branch down
    • place the next center (of the half) on one side, and the other side on the other
    • keep doing this until all of the elements are in the tree

3.11 Hacks:

  1. calculate the middle index and create a binary tree for each of these lists
    • 12, 14, 43, 57, 79, 80, 99
    • 92, 43, 74, 66, 30, 12, 1
    • 7, 13, 96, 111, 33, 84, 60
  2. Using one of the sets of numbers from the question above, what would be the second number looked at in a binary search if the number is more than the middle number?
  3. Which of the following lists can NOT a binary search be used in order to find a targeted value?

    a. ["amy", "beverly", "christian", "devin"]

    b. [-1, 2, 6, 9, 19]

    c. [3, 2, 8, 12, 99]

    d. ["xylophone", "snowman", "snake", "doorbell", "author"]

listone = [12, 14, 43, 57, 79, 80, 99]

middle = listone[int(len(listone)/2)]
print("The first middle index is: ", middle)

listtwo = [92,43,74,66,30,12,1]

listtwo.sort() #puts list in order

print(listtwo)

middle = listtwo[int(len(listtwo)/2)]
print("The second middle index is: ", middle)


listthree = [7, 13, 96, 111, 33, 84, 60]

listthree.sort() #puts list in order

print(listthree)

middle = listthree[int(len(listthree)/2)]
print("The third middle index is: ", middle)
The first middle index is:  57
[1, 12, 30, 43, 66, 74, 92]
The second middle index is:  43
[7, 13, 33, 60, 84, 96, 111]
The third middle index is:  60
    1. In the this list of numbers: 12, 14, 43, 57, 79, 80, 99: The second number looked at in a binary search if the number is more than the middle number would be 80.
    2. Second list: 1, 12, 30, 43, 66, 74, 92: The second number looked at would be 74.
    3. Third list: 7, 13, 33, 60, 84, 96, 111 The second number looked at would be 96
  1. The answer is C because the list is unsorted. In order to use the binary search, a user would have to sort the list like I have with the lists above.

How this helps me on my AP Exam

Lists are essential knowledge on the AP exam. In this lesson, I learn how to work with lists and different ways to achieve a desired outcome with a list. I learned about:

  • the different ways to edit a list
  • how to identify lists

I have also learned all about conditional statements. I can now identify the different conditional statements on the exam.