3.5-3.7 Student Lesson (group 3)

What is a boolean?

  • boolean = a denoting a system of algebraic notation used to represent logical propositions, especially in computing and electronics.
  • simple terms: determines if something is true or false
  • used in binary (0 = false and 1 = true)
score = 3
i = score
if i == 3:
    print("True") # either is true or false
else:
    print("False")
True

Hack 1: 3.5

[x] Explain in your own words what each logical operator does [x] Code your own scenario that makes sense for each logical operator

  • NOT: The NOT logical operator returns the opposite condtion of the data
  • AND: The AND logical operator determines if 2 conditions are met
  • OR: The OR logical operator determines if 1 of the conditions are met
ispassing = False
isstudentpassing = not(ispassing)
print(isstudentpassing)
temp = input("what is the temperature today?")
if int(temp) >= 40 and int(temp) <= 70:
    print("Bring a hoodie!")
if int(temp) < 40:
    print("bring snow gear!")
if int(temp) > 70:
    print("No jacket today!")
Bring a hoodie!
APscore = 4
Finalscore = 68
if APscore >= 3 or Finalscore >= 75:
    print("student passed this class")
else:
    print("student did not pass this class")
student passed this class

Notes

  • Selection: specific block of code that will execute (depending on algorithm condition returning true or false)
  • Algorithm: finite set of instructions that accomplish a specific task
  • Conditional Statement / If-Statement: statement that affects the sequence of control by executing certain statements depending on the value of a boolean (true or false)
  • Conditionals allow for the expression of algorithms that utilize selection without a programming language
    • "In which the code in block of statements is executed if the Boolean expression condition evaluates to true; no action is taken if condition evaluates to false"

Conditionals are ues in many languages

  • here is an example of one in Javascript:
if (30 == 7) {
    console.log("The condition is true")
}
else if (30 != 7) {
    console.log("The condition is false")
}

Hack 2: 3.6

[x] Level I: Vowel Count Return the number (count) of vowels in the given string. We will consider a, e, i, o, u as vowels for this challenge (but not y). The input string will only consist of lower case letters and/or spaces.

Hint: If you use a lot of if-statements and there are more than one outcome, that is to be expected. If not, don't panic, just keep trying.

[x] Level III: Mutliples of 3 or 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them).

Note: If the number is a multiple of both 3 and 5, only count it once.

Hint: What do you know about for loops? Since your code incorporates a list of numbers from 1 to the max number, can you use for loops along with conditionals?

[x] binary conditional logic [x] define key terms

Defining Key Terms:

  • Boolean: a boolean is an operator that determines if a condition is true or false
  • Selection: When an algorithm must make a decision (if a condition is met)
  • AND: AND is a logical operator that determines of 2 conditions are both met
  • OR: OR is a logical operator that determines if 1 of 2 conditions is met
  • NOT: NOT is a logical operator that displays the oposition condition of the data
gpa = 4.0
extracirriculars = "present"
if gpa >= 4.0 and extracirriculars == "present":
    major = input("What is your major")
    if major == "math" or major == "science":
        print("You have been accepted into our STEM program!")
    elif major == "english" or major == "history":
        print("You have been accepted into our arts program!")
    else:
        print("You have been accepted into our " + major + " program!")
else:
    print("I'm sorry, you are not accepted to this program")
You have been accepted into our STEM program!
# my first attempt at the Level 1 Challenge < better to not use the contians function
# also needs to iterate through to check every character (what if there are multiple of each vowel?)
word=input("Input a word to check how many vowels it has. ")
i == 0 #number of vowels
if word.__contains__("a"):
    i =+ 1
if word.__contains__("e"):
    i =+ 1
if word.__contains__("i"):
    i =+ 1
if word.__contains__("o"):
    i =+ 1
if word.__contains__("u"):
    i =+ 1

if i == 0:
    print("this word has no vowels")
else:
    print(i)
input_string = input("Input a string to check how many vowels it has. ")
vowelcount = 0
for character in input_string: #iterates through the string character by character
    if character == "a":
        vowelcount += 1
    elif character == "e":
        vowelcount += 1
    elif character == "i":
        vowelcount += 1
    elif character == "o":
        vowelcount += 1
    elif character == "u":
        vowelcount += 1
print(vowelcount)
4
numberstring = input("Input a number to find the sum of all the multiples of 3 or 5 below it. ")
numbertocheck = int(numberstring)
totalmultiples = 0
if numbertocheck >= 0: # if the number is negative it will display the sum as 0
    for n in range(numbertocheck+1):
        if n/3 == int(n/3): #checks for multiples of 3
            print(str(n) + " is a multiple of 3")
            totalmultiples += n    #elif prevents duplicates of numbers with both multiples of 3 and 5
        elif n/5 == int(n/5): # checks for multiples of 5
            print(str(n) + " is a multiple of 5")
            totalmultiples += n
print(totalmultiples)
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
15 is a multiple of 3
60

Hack 3

[x] For the first hack, pretend you are a school's test grader. Create an array with integers, each integer representing one score from a student's taken tests. If the average of the student's test scores are at least 75 percent, then display that the student is elligible for credit, and if not, display that the student must retake the tests over break. [x] The second hack is more number-oriented. Create an algorithm that calculates the sum of two numbers, then determines whether the sum is greater than or less than 100. [x] The hacks above was heavily derived from CollegeBoard. As a computer science student, you should be able to create an algorithm utilizing conditionals. Try something number-oriented if you get stuck. Creativity gets points.

def average(lst):
    return sum(lst)/len(lst)

gradelist = [92, 83, 90, 74, 86, 97]
averagegrade = average(gradelist)

print(str(averagegrade) + " is the student's grade average")

if averagegrade >= 75:
    print("student is eligible for credit")
else:
    print("student needs to retake tests during break")
87.0 is the student's grade average
student is eligible for credit
num1 = input("What is your first number?")
num2 = input("What is your second number?")
sumofnumbers = int(num1) + int(num2)
if sumofnumbers >= 100:
    print(str(sumofnumbers) + " is greater than or equal to 100")
else:
     print(str(sumofnumbers) + " is less than than 100")
7 is less than than 100
# to test if a show is included in Netflix, and if it is recommended
showdictionary = {
    'Wednesday':5,  # key=title name and value=rating out of 5 stars
    'You':3, 
    'Knight Before Christmas':4, 
    'Red Notice':5,
    'Truth or Dare':1
}
show = input("What show are you looking for?")
if show in showdictionary.keys():
    print(show + " is available on Netflix")
    if showdictionary[show] >= 3:
         print("show/movie is recommended")
    else:
        print("show is not recommended")
else:
    print(show + " is not available on Netflix")
You is available on Netflix
show/movie is recommended

Nested Conditions

  • conditional statements within conditional statements
  • called "nested" within another
  • else if inside of another ese if

Hack 4

[x] Create 3 differnt flow charts representing nested statements and transfer them into code. [x] Create a piece of code that displays four statements instead of three. Try to do more if you can. [x] Make piece of code that gives three different recommandations for possible classes to take at a school based on two different condtions. These conditions could be if the student likes STEM or not.

STEM = input("Are you intrested in STEM? Y or N")
if STEM == "Y":
    subject = input("Do you like math or science better?")
    if subject == "math":
        print("Class recommendations: Advanced Function Analysis, AP Calculus AB, AP Calculus BC, AP Statistics")
    if subject == "science":
        print("Class recommendations: Chemistry, Physics, AP Enviornmental Science, AP Physics, AP Chemistry")
else:
    language = input("Are you intrested in language? Y or N")
    if language == "Y":
        lansubject = input("Do you prefer a foreign language or English?")
        if lansubject == "foreign language":
            print("Class recommendations: Spanish, Mandarin, AP Spanish, AP Mandarin")
        if lansubject == "English":
            print("Class recommendations: American Literature, AP English Literature")
    if language == "N":
        print("See class list for more options!")
Class recommendations: Advanced Function Analysis, AP Calculus AB, AP Calculus BC, AP Statistics

Flowchart #1: Is it cold?

temp = input("what is the temperature today?")
if int(temp) <= 73:
    print("It is cold!")
    if int(temp) <= 40:
        print("Bring a snow jacket!")
    else:
        print("Bring a hoodie!")
else:
    print("It's warm today! Don't bring a jacket :)")
It is cold!
Bring a snow jacket!

Flowchart #2: Is the class difficult?

passingrate = 72
testaverage = 82
if passingrate > 70 and passingrate <= 100:
    if testaverage >= 80:
        print("This class is not difficult")
    else:
        print("this class is difficult")
else:
    print("this class is difficult")
This class is not difficult

Flowchart #3: Should Alexa work at school during first period off roll?

feeling = input("Are you tired today?")
if feeling == "yes":
    print("Stay home and sleep")
if feeling == "no":
    homework = input("Do you have homework to do?")
    if homework == "yes":
        print("Go to school")
    else:
        print("Stay home and sleep")
Stay home and sleep
drinkable = "potable"
temperature = "warm"
if drinkable == "potable":
    print("water is potable")
    if temperature == "cold":
        print("water is " + str(temperature)) 
        print("water is in ideal condition")
        print("drink up!")
    else:
        print("water is " + str(temperature)) 
        print("water is not in ideal condition")
        print("chill with ice")
else:
    print("do not drink, water is not potable")
water is potable
water is warm
water is not in ideal condition
chill with ice

3.8-3.10 Student Lesson (group 4)

  • 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
  • while loops = similar outpytut with variation in input
  • similar to for loop (requires a variable which is the starting value)

Hacks Unit 3 Section 3.8.1

  1. Define an Iteration
  2. Make your own example of an iteration with at least 4 steps and a stopping condition(Similar to mine that I did)
  3. Program a simple iteration.
  • Iteration: loop that continues repeating until condition is met
  • Example of iteration with stopping condition:
    • I am doing an easter egg hunt and trying to frind the golden egg. I have split the searching area into sections
    1. I walk to a section
    2. I look aroung to try and find the golden egg
    3. If it is not there, I add one to the section number (move onto next section)
    4. I repeat steps 1 through 4
    5. Once I find the egg, I stop searching to go brag to the kids
hourshomework = 0
while hourshomework < 8:
    print("Too easy")
    hourshomework += 1
    if hourshomework == 6:
        break
Too easy
Too easy
Too easy
Too easy
Too easy
Too easy

Hacks Unit 3 Section 3.8.2

  1. What is an iteration statement, in your own words?
  2. Create a descending list of numbers using for loop
  3. Using while loop, make a list of numbers which will form an output of 3,16,29,42,55,68,81
  • Iteration statement: a condition that must be met in a loop or it will continue repeating

Lists Commands

  • append() - adding element to the end of the list
  • insert() - adding an element in a specific position
  • remove() - remove an item from the list
  • len() - returns the number of items in a list
  • sort() - changes order of list permanently
  • sorted() - returns a copy of the list which leaves the original copy unchanged
  • range() - use to work with number efficiently
  • min() - find the least value in list
  • max() - find the highest value in list
  • sum() - sum of all in list
numlist = [50]
for i in numlist:
    i -= 1
    numlist.append(i) # using append to add to the end of a list
    if i == 0:
        break
print(numlist)
[50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
i = 3
print(i)
while i <= 68:
    i += 13
    print(i)
3
16
29
42
55
68
81

Find the lowest value in a 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"]
min = 20
for n in nums:
    if int(n) < int(min):
        min = n
print(min)
10
import getpass, sys
import random

def ask_question (question, answer):

    print(question)
    ans = input(question)
    print(ans)
   
    if ans == answer:
        print("Correct!")
        return 1

    else:
        print("Wrong")
        return 0

question_list = ["What allows a value to be inserted into a list at index i?" , "What allows an element at index i to be deleted from a list?" , "What returns the number of elements currently in a specific list?" , "What allows a value to be added at the end of a list?"]
answer_list = ["index()", "remove()", "length()" , "append()"]

# Set points to 0 at the start of the quiz
points = 0

# If the length of the quiz is greater than 0, then random questions will be chosen from the "question_list" set
while len(question_list) > 0:
    index = random.randint(0, len(question_list) - 1)
    
# The points system where a point is rewarded for each correct answer    
    points = points + ask_question(question_list[index], answer_list[index])
    
# If a question or answer has already been used, then it shall be deleted    
    del question_list[index]
    del answer_list[index]

# Calculating score using the points system and dividing it by the total number of questions (6)
score = (points / 4)

# Calculating the percentage of correct answers by multiplying the score by 100
percent = (score * 100)

# Printing the percentage, and formatting the percentage in a way where two decimals can be shown (through "{:.2f}")
print("{:.2f}".format(percent) + "%")

# Adding final remarks based upon the users given scores
if points >= 5:
         print("Your total score is: ", points, "out of 4. Amazing job!")

elif points == 4:
         print("Your total score is: ", points, "out of 4. Not too bad, keep on studying! " )

else:
         print("Your total score is: ", points, "out of 4. Its alright, better luck next time!")
What allows an element at index i to be deleted from a list?
remove()
Correct!
What allows a value to be added at the end of a list?
append()
Correct!
What returns the number of elements currently in a specific list?
length()
Correct!
What allows a value to be inserted into a list at index i?
index()
Correct!
100.00%
Your total score is:  4 out of 4. Not too bad, keep on studying! 
monthly_earnings = []

a = 0
while a == 0:
    money = input("How much money did you make this month?")
    if money == "":
        break
    monthly_earnings.append(int(money)) # uses append()

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

if sort == "yes":
    print("sorted:")
    print(sorted(monthly_earnings)) # uses sorted() which returns a copy of list
else:
    print("unsorted:")
    print(monthly_earnings)
print("Your highest monthly earning is $" + str(max(monthly_earnings))) #uses max()
print("You have been working for " + str(len(monthly_earnings)) + " months")
sorted:
[2, 42, 3256, 5000]
Your highest monthly earning is $5000
You have been working for 4 months

3.9 and 3.11 Student Lesson (group 5)

3 components to an algorithm:

  • selection
  • sequence
  • iteration
  • Algorithms can be written is different ways but work the same way!
  • Why is it important to know that algorithms that look different can do the same thing and that algorithms that look the same might have different results?
    • This knowledge is important since it will cause people to look at and compare code more carefully. We can catch mistakes, make code more efficient, and overall learn from others. Mistakes are learning too!
# code #1
print("What Grade Did You Get?")
grade = int(input("Enter Grade:"))
if grade >= 90:
        print("Wow! Good job!")
elif 70 < grade < 90:
        print("Nice!")
elif grade < 70:
        print("Do Better")
What Grade Did You Get?
Wow! Good job!
print("What Grade Did You Get?")
grade = int(input("Enter Grade:"))
A = grade >= 90
B = 70 <= grade < 90
C = grade < 70
if A:
        print("Wow! Good job!")
elif B:
        print("Nice!")
elif C:
        print("Do Better")
What Grade Did You Get?
Wow! Good job!

Nested Conditionals

isalexatired = True
havehw = True

if isalexatired == True and havehw == False:
    print("Stay home and sleep!")
else:
    if havehw == True:
        print("Go to school")
    else:
        print("Stay home and sleep!")

# Boolean conversion
gotoschool = not(isalexatired) or isalexatired and havehw
if gotoschool == True:
    print("Go do you work at school!")
if gotoschool == False:
    print("Stay home and sleep queen")
Go to school
Go do you work at school!

Developing Algorithms

  • good to outline process before coding
  • make sure everything is sequenced correctly! (goes through in intended order)
  • should make a flow chart or use natural language

Natural Language for Netflix Code

  1. Input what show user is looking for
  2. check if show is in showdictionary
  3. If it is in dictionary, move onto step 4. If not, print "show is not available on Netflix"
  4. check if the show has a rating of 3 or higher
  5. If it does, print "show is recommended"; if it doesn't print "how is not recommended"
showdictionary = {
    'Wednesday':5,  # key=title name and value=rating out of 5 stars
    'You':3, 
    'Knight Before Christmas':4, 
    'Red Notice':5,
    'Truth or Dare':1
}
show = input("What show are you looking for?")
if show in showdictionary.keys():
    print(show + " is available on Netflix")
    if showdictionary[show] >= 3:
         print("show/movie is recommended")
    else:
        print("show is not recommended")
else:
    print(show + " is not available on Netflix")
You is available on Netflix
show/movie is recommended

Pre-Existing Algorithms

  • can be helpful to use pre-exsiting functions
  • common and simple ones include:
    • determining min or max of two or more numbers
    • computing the sum or average
    • identifying if an integer is even or odd
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():
    guessednum = input("Choose a number!")
    return guessednum 

#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("You guessed too low") 
        lower_bound = guess
        return lower_bound, upper_bound
    elif int(guess) > int(number):
        print("You guessed too high")
        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 78.
You guessed too high
Guess a number between 0 and 78.
You guessed 34.
You guessed too low
Guess a number between 34 and 78.
You guessed 45.
You guessed too high
Guess a number between 34 and 45.
You guessed 56.
You guessed too high
Guess a number between 34 and 56.
You guessed 38.
You guessed too low
Guess a number between 38 and 56.
You guessed 42.
You guessed too low
Guess a number between 42 and 56.
You guessed 43.
You guessed the number in 7 guesses!
  • what is it?: repeatedly dividing a search interval in half
  1. put the numbers in order
    • ascending
    • descending
  2. find the middle number first

    • this is found by taking the highest index number plus the lowest index number and divide by 2
  3. the numbers on the right will be greater and the numbers on the left will be smaller

    • this can be represented with a binary tree
      • middle number with the smaller number branched off on the left and bigger numbers branched off on the right
  • these lists are not always numbers
    • lists can be made with strings
    • ex. ["apple", "banana", "cherry", "peach", "watermelon"]
    • alphabetical order
      • a-z
      • z-a
index = [12, 14, 43, 57, 79, 80, 99]
index.sort()
mid = int(len(index) / 2) 
print(mid)
print("middle is",index[mid])
3
middle is 57

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 of the vocabulary:

  • 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
# to test if a show is included in Netflix, and if it is recommended < this is anm example of an algorithm
showdictionary = { #this is a dictionary
    'Wednesday':5,  # key=title name and value=rating out of 5 stars
    'You':3, 
    'Knight Before Christmas':4, 
    'Red Notice':5,
    'Truth or Dare':1
}
# this is an example of sequencing (order matters) and selection (of and else statements)
show = input("What show are you looking for?") # this is an example of a variable, the "=" is the assignment operator
# this variable has the data type of a string
if show in showdictionary.keys(): # this is an if statement in python
    print(show + " is available on Netflix")
    if showdictionary[show] >= 3: # this is a nested selection statement
         print("show/movie is recommended")
    else: # this is an example of an else statement in python, it will only apply if the previous if condition isn't met
        print("show is not recommended")
else:
    print(show + " is not available on Netflix")
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!")
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)
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)
[50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]