Lesson 3.5 Finn/Jake

What is a Boolean

  • The defention of a Boolean is a denoting a system of algebraic notation used to represent logical propositions, especially in computing and electronics.
  • A boolean expresions are either true or false.
  • Testing if two numbers or variables are equal is a common example.
  • For example: The sky is blue = True
  • What do we use to represent them? (Hint think of how domain/range of graph is answered)
  • How is binary related to this?
  • How could this be used when asked a question?

Examples (Not part of homework)

Type the code down below for these two example

  • Try to make a statement that determines if a variable "score" is equal to the number 3
  • Try to make this score variable have an output if it equals 3
# The code for ex:1

# The code for ex:2

Relational Operators

  • The mathmatical relationship between two variables
  • Determines an output on whether or not the statement is true
  • a=b, a>b, etc.

Examples (Not part of homework)

Type the code down below for these two example

  • You have to be the age of 16 or older to drive
  • Each rollercoaster cart holds 4 for people per cart
# Put the code for ex:1
 
# Put the code for ex:2

Logical Operators

NOT

  • NOT, it displays the opposite of whatever the data is. Mainly used for true/false, and does not effect the variable.
isRaining = False
result = not(isRaining)
print(result)
True

AND

  • AND, used to evaulte two conditions together and determine if both condintions are met
grade = 95
if grade > 70 and grade <= 100:
    print("You passed the quiz")
You passed the quiz

OR

  • OR, when using or the function only looks to see if one of the conditions is met then will
lives = 1
score = 21
if lives <= 0 or score > 20:
    print("end game")
end game

Hacks

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

Conditionals

Paaras Purohit and Shruthi Damodar
  • title: Conditionals
  • toc: true
  • categories: [tri2lesson]
  • permalink: /conditionals
  • tags: [tri2lesson]

Learning Objectives / Some Things You Might Want to Keep Note Of

  • Conditionals allow for the expression of algorithms that utilize selection without a programming language.
  • Writing conditional statements is key to computer science.
  • Determine the result of conditional statements

Key Terms

  • Selection: The specific block of code that will execute depending on the algorithm condition returning true or false.
  • Algorithm: "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 the value of a boolean.

Conditional Statements in JavaScript

Below is an example of an algorithm in JavaScript that uses selection:

function isEven(parameter) {
    if (parameter % 2 == 0) {
        console.log("The number is even.");
    }
    else if (parameter % 2 != 0) {
        console.log("The number is odd.")
    }
}

isEven(4)
  Cell In[23], line 1
    function isEven(parameter) {
             ^
SyntaxError: invalid syntax

A computer science student such as yourself will see conditional statements in JavaScript a lot. Below is an example of one in action:

if (30 == 7) {
    console.log("The condition is true")
}
  Cell In[5], line 1
    if (30 == 7) {
                 ^
SyntaxError: invalid syntax

That is one conditional statement, but this algorithm is too simple to have anything done with it. Below is an algorithm building on the previous algorithm:

if (30 == 7) {
    console.log("The condition is true")
}
else if (30 != 7) {
    console.log("The condition is false")
}
  Cell In[21], line 1
    if (30 == 7) {
                 ^
SyntaxError: invalid syntax

Conditional statements can be used for many a purpose. The algorithm above was quite simple, but conditionals can be found in more complex algorithms.

Binary Numbers

Let's do some truth tables!

Speed round

Challenges

Note: I did these in Python

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.

Level II: Who Likes It?

You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement the function which takes an array containing the names of people that like an item. It must return the display text as shown in the examples:

[] --> "no one likes this"

["Peter"] --> "Peter likes this"

["Jacob", "Alex"] --> "Jacob and Alex like this"

["Max", "John", "Mark"] --> "Max, John and Mark like this"

["Alex", "Jacob", "Mark", "Max"] --> "Alex, Jacob and 2 others like this"

Note: For 4 or more names, the number in "and 2 others" simply increases.

Hint: This requires you to combine knowledge on lists along with the conditionals you learned in this lesson.

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?

Level IV: Likes vs. Dislikes

YouTube had a like and a dislike button, which allowed users to express their opinions about particular content. It was set up in such a way that you cannot like and dislike a video at the same time. There are two other interesting rules to be noted about the interface: Pressing a button, which is already active, will undo your press. If you press the like button after pressing the dislike button, the like button overwrites the previous "Dislike" state. The same is true for the other way round.

Create a function that takes in a list of button inputs and returns the final state.

Examples:

/*
like_or_dislike([Dislike])  Dislike
like_or_dislike([Like, Like])  Nothing
like_or_dislike([Dislike, Like])  Like
like_or_dislike([Like, Dislike, Dislike])  Nothing
*/

Notes

  • If no button is currently active, return Nothing.
  • If the list is empty, return Nothing.

Hint: This is like level III, but harder, so don't give up!

Level V: Find the Odd Number

Given an array of integers, find the one that appears an odd number of times.

There will always be only one integer that appears an odd number of times.

Examples:

[7] should return 7, because it occurs 1 time (which is odd).

[0] should return 0, because it occurs 1 time (which is odd).

[1,1,2] should return 2, because it occurs 1 time (which is odd).

[0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).

[1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).

Hint: This is by far the hardest challenge out of all of these, in my opinion, and it took me about 3 or 4 months to solve this one.

Hacks

  • 1 point for defining all the key terms in your own words. 0.5 points if you use examples that show you truly understand it.
  • 1 point for writing a program that uses binary conditional logic. 0.5 points if it is original and shows complexity
  • 1 extra point for each challenge that you program or pair program.
  • 0.5 points for your review ticket looking nice, or you convincing me that it does.
  • 1 point for each and any extra work you do that helps show your understanding of conditionals.

Lesson 3.7 James

Nested Conditionals

  • Nested conditional statements consist of conditional statements within conditional statements
  • they're nested one inside the other
  • An else if inside of another else if
  • Can be used for a varying amount of "else if statements." The first if statement can represent if two coditions are true. The first else if can represent if only one or the other is true. The last else if represents if neither of the conditions are true.
  • Can have three different conditions

Take aways

  • Learn how to determine the result of nested condtional statements
  • Nested conditional statements consist of conditional statements within conditional statements
  • One condition leads to check in a second condition

Writing Nested Conditional Statements

  • Can be planned and writen out first
  • Flow chart is a possibility. Ask a question. If the statement is false end the flowchart with one result. If it is true then repeat the process once more.
  • If (condition 1)
  • {
    • first block of statements
  • }
  • else
  • {
    • IF (condition 2)
    • {
      • second block of statements
    • }
  • }

this statement is false make a new result. Finally if the statement is true make a final result

Question 1

Look at the following code

  • what happens when x is 5 and y becomes 4? Is the output same or change?
x = 2
y = 3
if x == y:
    print("x and y are equal")
else:
    if x > y:
        print("x is bigger than y")
    elif x < y:
        print("x is smaller than y")

Question 2

  • How much it will be cost when the height will be 60, age is 17, and photo taken?
  • when this person came after 1 year how much it will be cost?
height = int(input("Welcom to the rollercoaster! \nWhat is your height in Inch? "))
age = int(input("What is your age?"))
if height < 48 :
   print("Can't ride")
elif age < 12 :
  photo = input("Adult tickets are $5 \nDo you want a photo taken? Y or N. ")
  if photo=="Y":
    print("The total bill is $8.")
  if photo=="N":
    print("The total bill is $5.")
elif age < 18:
   photo = input("Adult tickets are $7 \nDo you want a photo taken? Y or N. ")
   if photo=="Y":
    print("The total bill is $10.")
   if photo=="N":
    print("The total bill is $7.")
else :
   photo = input("Adult tickets are $12 \nDo you want a photo taken? Y or N. ")
   if photo=="Y":
    print("The total bill is $15.")
   if photo=="N":
    print("The total bill is $12.")
The total bill is $15.

Let's look at Examples

import random
global i
game = ["rock", "scissor", "paper"]
winning = ["paper", "rock", "scissor"]
i = 0
def gameStart():
    randomNumber = random.randrange(0,2)
    randomOne = game[randomNumber]
    gamer = str(input("what will you do"))
    print(gamer)
    print(randomOne)
    while True:
        if winning[i] == gamer:
            break
        else:
            i += 1
    if randomNumber == i:
        print("You win")
    else:
        if randomNumber == (i+1)%3:
            print("Lose")
        elif randomNumber == (i+2)%3:
            print("Draw")
    pre = input("Do you want a game?[yes/no]")
    if pre == "yes":
        gameStart()
        randomNumber = random.randrange(0,2)
    else:
        print("Goodbye")
gameStart()
rock
scissor
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Cell In[9], line 30
     28     else:
     29         print("Goodbye")
---> 30 gameStart()

Cell In[9], line 13, in gameStart()
     11 print(randomOne)
     12 while True:
---> 13     if winning[i] == gamer:
     14         break
     15     else:

UnboundLocalError: local variable 'i' referenced before assignment

Binary Math with Conversions
4
Plus Binary Octal Hexadecimal Decimal Minus
00000000 0 0 0
00000000 0 0 0
00000000 0 0 0

Hacks

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

Rubric for hacks:

  • Each section is worth .33 and you will get + 0.01 if all are completed to have full points.

How to get a .33

  • All hacks are done for the section, fully completed.

How to get a .30

  • Not all hacks are done in the section

Below a .30

  • Sections are missing/incomplete