Featured

Probability Distribution Example [w/ the NYC Tree Census]

by 5:21 PM
Probability distributions take samples from a population, calculating the proportions of a certain item within each sample in order to estimate the parameter proportion. The parameter proportion is defined to be the actual proportion within the sample. The sample size of the amount of samples you take from the population for each collection of items (for your estimate) has a significant impact on your ability to predict the proportion. This can be demonstrated with a simple computer simulation.

London Planetree. Source
According to the 2015 NYC Tree Census, the most popular tree is the London planetree with 87014 member out of a total of 683788 total individual trees. This means our true parameter is 12.7%. In order to better estimate the figure from our proportion distribution, we will need to essentially make sure our probability distribution is normal.

This is accomplished via the normality test which states that: n*p >= 10 && n*(1-p) >= 10

where n is the sample size and p is the true proportion (parameter). If you aren't sure what p is, you will eventually reach a normal curve by increasing the sample size and re-running your simulation. You will also want to make sure that you are drawing samples from the same population each time you draw a sample (maintaining independence).

This principle is at work in the following example with the London planetrees:

Proportion of the London Planetree in the 2015 NYC Tree Census (n=5)
Since 5*.127 is not greater than ten, this simulation produces a graph that lacks normality.

Proportion of London Planetree in the 2015 NYC Tree Census (n=20)
Although 20*.127 is still not greater than ten, this simulation produces a graph that is closer to normal and less skewed than the previous example. This indicates that we are closer to achieving to our goal as we increase sample size. 

Proportion of London Planetree in the 2015 NYC Tree Census (n=200)
Since 200*.127>10, the condition for normality has been reached and we can form better estimates for the actual parameter proportion. 

Bonus Graphs (Sample Proportions for the 1995 and 2005 Census):

Proportion of London Planetree in the 2005 NYC Tree Census (n=200)
Proportion of London Planetree in the 1995 NYC Tree Census (n=200)
Feel free to remix the code with the three different datasets to try out these simulations for yourself (i.e. utilizing simulations for probability distributions).

Program Code


import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter 
import numpy as np
from numpy.random import choice

def getKey(item):
    return item[1]

def main():
    treeStuff = pd.read_csv("new_york_tree_census_2015.csv")
    treeSpecies = list(treeStuff["spc_common"])
    treeSpeciesCombined = Counter(treeSpecies)
    j = sorted(treeSpeciesCombined.items(),key=getKey)
    treeSpecies2 = []
    treeCount = []
    for i in j:
        i = list(i)
        if (isinstance(i[0],float)):
            i[0] = "Unknown"
        treeSpecies2.append(i[0])
        treeCount.append(i[1])
    counts = []
    for k in range(0,1000):
        draw = choice(treeSpecies2, 200, p = [x / float(sum(treeCount)) for x in treeCount]) # where you set sample size
        count = sum(np.char.count(draw,sub="London planetree"))
        counts.append(count/float(len(draw)))
    probabilities = Counter(counts)
    l = sorted(probabilities.items())
    probCategories = []
    probValues = []
    for r in l:
        r = list(r)
        probCategories.append(r[0])
        probValues.append(r[1])
    x_pos = [e for e, _ in enumerate(probCategories)]
    plt.xticks(x_pos, probCategories,rotation='vertical')
    plt.xlabel("Proportion of London Planetree in a Sample")
    plt.ylabel("Number of Samples")
    plt.title("1000 Simple Random Sample's from 2015 NY Tree Census (n=200)")
    plt.bar(x_pos,probValues)
    plt.show()
    
main()

Data Source: See this file on Kaggle for the NYC Tree Census Data. 

Creating an Online Repository of Searchable Scratch Forum Data (Process + Results)

by 6:53 PM
Challenge


Currently the Scratch Forums does not have a functional search bar that permits users to filter through the metadata associated with the different threads.

"Search 'Results' Appearing as a Blank Table"
Users may be interested in such a feature in order to find historical tutorials/helpful posts on certain subjects, examine the contributions of other Scratchers, and find inspiration for their own projects. This project aims to provide a means for individuals to accomplish this task easily and effectively.

Process

The data from the forums is imported as raw HTML and processed via the beautifulsoup library.  Once the relevant information is extracted, it is placed into a sqlite3 database. This was published to a heroku web applet via the datasette JavaScript Library.

Results


The final product is located at this web address. The metadata is separated into tables representing all thirty-six public forums. You can search each of the columns with a variety of boolean operators and download processed data in a JSON or CSV file format.

Future Steps 

  • Updating Script - figure out a way to dynamically update the web page automatically on a regular basis. 
  • No manual extraction of data - currently the script requires that you supply the number of pages for a given forum. This process could be automated within the program in the future. 

Code - Python


# coding=utf-8

"""
Definition: Scratch Discussion Forum Database Generator
"""

from bs4 import BeautifulSoup

import requests

import sqlite3

def extractData(numberOfPages,forumID,conn,c,forum):
    
    for j in range(1,numberOfPages+1):
        
        while True:  
            r  = requests.get("https://scratch.mit.edu/discuss/" + str(forumID) + "/?page=" + str(j))
            if (r.status_code == 200):
                break
            
        data = r.text
            
        soup = BeautifulSoup(data, 'lxml')             
        
        soup = soup.find(id="pagewrapper")
    
        soup = soup.find(id = "content")
    
        soup = soup.find(id = "vf")

        soup = soup.div
         
        soup = soup.find("div", {"class": "box-content"})
           
        soup = soup.contents[1]
    
        soup = soup.contents[3]
    
        while (soup.contents.count(u'\n')): 
            soup.contents.remove(u'\n')
    
        for i in range(0,len(soup.contents)):
            newSoup = soup.contents[i]
            if (newSoup.find("div", {"class" : "isticky"}) == None): # Q: Is the topic stickied?
                stickied = "No"
            else:
                stickied = "Yes"
            if (newSoup.find("div", {"class": "iclosed"}) == None): # Q: Is the topic open or closed?
                closed = "No"
            else:
                closed = "Yes"
            latestTimeStamp = newSoup.find("td", {"class": "tcr"}).a.string #Latest Post Timestamp
            if ("Today" in latestTimeStamp):
                latestTimeStamp = latestTimeStamp.replace("Today","Dec. 23, 2019") #replace with today's date
            if ("Yesterday" in latestTimeStamp):
                latestTimeStamp = latestTimeStamp.replace("Yesterday","Dec. 22, 2019") #replace with yesterday's date
            topicTitle = newSoup.find("h3", {"class": "topic_isread"}).string #Title of the Topic 
            topicAuthor = newSoup.find("span", {"class": "byuser"}).string[3:] #Author of the Topic
            topicLink = "https://scratch.mit.edu" + newSoup.find("h3", {"class": "topic_isread"}).a['href'] # Link to the topic
            numberOfReplies = newSoup.find("td", {"class": "tc2"}).string # Number of Replies
            numberOfViews = newSoup.find("td", {"class": "tc3"}).string # Number of Views
            latestPostLink = "https://scratch.mit.edu" + newSoup.find("td", {"class": "tcr"}).a['href'] #Latest Post Link
            latestPostAuthor = newSoup.find("td", {"class": "tcr"}).find("span", {"class":"byuser"}).string[3:] #Latest Post Author
            #insert = "(" + "'" + stickied + "'" + "," + "'" + closed + "'" + "," + "'" + topicTitle + "'" + "," + "'" + topicAuthor + "'" + "," + "'" + topicLink + "'" + "," + numberOfReplies + "," + numberOfViews + "," + "'" + latestPostLink + "'" + "," + "'" + latestTimeStamp + "'" + "," + "'" + latestPostAuthor + "'" + ")" 
            c.execute("INSERT INTO " + forum + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(stickied, closed, topicTitle, topicAuthor, topicLink, numberOfReplies, numberOfViews, latestPostLink, latestTimeStamp, latestPostAuthor))            
            
        conn.commit()
        
        print(j)

def main(): 
    
    conn = sqlite3.connect('scratchForumPosts.db')
    
    c = conn.cursor()
    
    c.execute('''CREATE TABLE announcements(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 
    
    # FORMAT: (Number of Pages, Forum ID, SQLite Database Var., SQLite Database Cursor Var., Forum Database Storage Table Name)
    
    extractData(11,5,conn,c,"announcements") # Announcements Forum
    
    c.execute('''CREATE TABLE newScratchers(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(316,6,conn,c,"newScratchers") # New Scratchers Forum
    
    c.execute('''CREATE TABLE helpWithScripts(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(1913,7,conn,c,"helpWithScripts") # Help With Scripts Forum

    c.execute('''CREATE TABLE showAndTell(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(2458,8,conn,c,"showAndTell") # Show and Tell Forum
    
    c.execute('''CREATE TABLE projectIdeas(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(325,9,conn,c,"projectIdeas") # Project Ideas Forum
    
    c.execute('''CREATE TABLE collaboration(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(612,10,conn,c,"collaboration") # Collaboration Forum
    
    c.execute('''CREATE TABLE requests(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(571,11,conn,c,"requests") # Requests Forum
    
    c.execute('''CREATE TABLE questionsAboutScratch(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(1199,4,conn,c,"questionsAboutScratch") # Questions About Scratch Forum
    
    c.execute('''CREATE TABLE suggestions(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(943,1,conn,c,"suggestions") # Suggestions Forum
    
    c.execute('''CREATE TABLE bugsAndGlitches(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''')

    extractData(1023,3,conn,c,"bugsAndGlitches") # Bug and Glitches Forum
    
    c.execute('''CREATE TABLE advancedTopics(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(185,31,conn,c,"advancedTopics") # Advanced Topics Forum
    
    c.execute('''CREATE TABLE connectingToThePhysicalWorld(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(28,32,conn,c,"connectingToThePhysicalWorld") # Connecting to the Physical World Forum
    
    c.execute('''CREATE TABLE developingScratchExtensions(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''')  

    extractData(16,48,conn,c,"developingScratchExtensions") # Developing Scratch Extensions Forum
    
    c.execute('''CREATE TABLE openSourceProjects(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(7,49,conn,c,"openSourceProjects") # Open Source Projects Forum
    
    c.execute('''CREATE TABLE thingsIAmMakingAndCreating(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(284,29,conn,c,"thingsIAmMakingAndCreating") # Things I'm Making and Creating Forum
    
    c.execute('''CREATE TABLE thingsIAmReadingAndPlaying(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(385,30,conn,c,"thingsIAmReadingAndPlaying") # Things I'm Reading and Playing Forum
    
    c.execute('''CREATE TABLE africa(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(1,55,conn,c,"africa") # Africa Forum
    
    c.execute('''CREATE TABLE bahasaIndonesia(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(2,36,conn,c,"bahasaIndonesia") # Bahasa Indonesia Forum
    
    c.execute('''CREATE TABLE català(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''')  

    extractData(2,33,conn,c,"català") # Català Forum
    
    c.execute('''CREATE TABLE deutsch(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(48,13,conn,c,"deutsch") # Deutsch Forum
    
    c.execute('''CREATE TABLE ελληνικά(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(7,26,conn,c,"ελληνικά") # Ελληνικά Forum
    
    c.execute('''CREATE TABLE español(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(45,14,conn,c,"español") # Español Forum
    
    c.execute('''CREATE TABLE français(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(152,15,conn,c,"français") # Français Forum
    
    c.execute('''CREATE TABLE עברית(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(3,22,conn,c,"עברית") # Hebrew Forum 
        
    c.execute('''CREATE TABLE 한국어(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(81,23,conn,c,"한국어") # 한국어 Forum
    
    c.execute('''CREATE TABLE italiano(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(35,21,conn,c,"italiano") # Italiano Forum
    
    c.execute('''CREATE TABLE nederlands(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(15,19,conn,c,"nederlands") # Nederlands Forum
    
    c.execute('''CREATE TABLE 日本語(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(117,18,conn,c,"日本語") # 日本語 Forum
    
    c.execute('''CREATE TABLE norsk(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(1,24,conn,c,"norsk") # Norsk Forum
    
    c.execute('''CREATE TABLE polski(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(56,17,conn,c,"polski") # Polski Forum
    
    c.execute('''CREATE TABLE português(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(19,20,conn,c,"português") # Português Forum
    
    c.execute('''CREATE TABLE Pусский(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(37,27,conn,c,"Pусский") # Pусский Forum
    
    c.execute('''CREATE TABLE türkçe(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(25,25,conn,c,"türkçe") # Türkçe Forum
    
    c.execute('''CREATE TABLE 中文(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(62,16,conn,c,"中文") # 中文 Forum
    
    c.execute('''CREATE TABLE otherLanguages(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(14,34,conn,c,"otherLanguages") # Other Languages Forum
    
    c.execute('''CREATE TABLE translatingScratch(Stickied text, Closed text, Title text, Author text, Link text, Replies real, Views real, LatestPostLink text, LatestPostTimestamp text, LatestPostAuthor text)''') 

    extractData(10,28,conn,c,"translatingScratch") # Translating Scratch Forum
    
    conn.close()
    
main()

Code - Command Line


datasette publish heroku scratchForumPosts.db -n scratchdiscussionforums

Syntax-highlighted text box generated with hilite.me.

The Lewis Dot Structure for O2

by 6:39 PM
Created by MakeTheBrainHappy.
This is the Lewis Dot Structure for O2, commonly referred to as oxygen gas. Due to oxygen's high electronegativity (affinity for electrons), the pure element is nearly exclusively found in either this state or ozone (O3 - a distinct lewis structure for another post). When drawing the structure, you may replace the individual lines with two dots symbolizing the two electrons contained within the bond. By sharing two electrons each, both atoms fill their valence shells with eight electrons as required under the octet rule for the first three lines of the periodic table. Since this is the double bond, the two atoms create a sigma-pi "sp" hybridized linear bond.

Due to these properties, the molecule is generally considered nonpolar. Between these two atoms, there is no electronegativity difference which means that O2 molecules only interact via weak London Dispersion forces. This leads to the stable confirmation which naturally exists in the atmosphere.

The importance of this element within our chemical systems cannot be understated. Oxygen is the most abundant element on earth, constituting nearly half of the atmosphere and crust [1] and the most abundant element in the universe after hydrogen and helium.

Liquid and Solid Oxygen?

Credit to the Eielson Air Force Base
Although it does not gain as much notoriety as its counterpart liquid nitrogen, a liquified version of oxygen does exist and is most notably utilized for liquid-powered rockets. Liquid oxygen in fact has a lower boiling point (at 90K) than liquid nitrogen (at 77K); however, liquid oxygen reacts violently with organic materials which limits its potential biological applications. Solid oxygen is also theoretically possible to create at a temperature of approximately 55 K.

Importance of Oxygen in Carbon Cycling

Diagram created by eSchoolToday
The carbon cycle is traditionally thought of as an producer-consumer relationship with the autotroph (i.e. photosynthesizing orgasm) requiring an input of CO2 (generally) and outputting O2 in the process. The consumer then utilizes some of the released O2 for respiration. While this generally encapsulates the relationship, more complex theories will touch upon the role of decomposers within both photosynthetic and oceanic "sinks" of carbon.

Diagram from the NASA Earth Observatory
The "Oxygen" Revolution
Figure from a professor at the University of Waterloo 
Oxygen has not always been a significant component of earth's atmosphere. In fact, its rapid appearance can be attributed to the emergence of respirating autotrophs releasing oxygen into the atmosphere. However, these same forms of life that were releasing this gas needed to evolve mechanisms to avoid its dangerous effects toward the forms of life which existed at that time due to the drastic change in the atmosphere. Some scientists have termed this occurrence as the "Great Oxygen Event" with numerous hypothesis as its effect on biological life nearly two billion years ago.

[1] https://openstax.org/books/chemistry-2e/pages/1-2-phases-and-classification-of-matter

Introduction to Object Oriented Programming in Scratch

by 6:53 PM
The Scratch Stage is a coordinate grid with an x-axis and a y-axis. 


Every Sprite has a position on the stage. Sprites can be considered Objects on the stage. Every position is represented by a coordinate point with an x- and y coordinate. 
As mentioned in the graphic on page one, the stage has limits with the x-coordinates b/t -240 to 240 and the y-coordinates b/t -180 to 180.
There are multiple blocks to travel around the stage. 
Feel free to experiment with them!



All sprites have certain object data associated with them:


These can be used like any other regular variables. The idea of direction is new, but it refers to the orientation of the sprite (which way it is facing). All of these data points refer specifically to the current state of the sprite. In order to save states, you need to use a variable.



Rotation: Scratch provides commands to change the current “direction” of the sprite. 


This block allows you to point/rotate the sprite to your mouse cursor.
Relative Motion: Many blocks will change the position or direction of the Sprite based on the current position and direction.  








This will move ten steps (units) in whatever the current direction is.








This block will create relative linear motion on the edges of the stage (i.e. the bounce. Experiment with it. 





There are three ways that the sprite can rotate:
All Around: can face any direction
Left-Right: only either faces 0 degrees or 180 degrees
Don’t Rotate: like it says, direction doesn’t change

Exercises:

Move the sprite to (90,90), then glide it to (-90,90) in one second, then move it to (-90,-90) and lastly glide it to (90,-90) in one second.
Draw a sphere in the costume section and use left arrow key & right array key to control rotational movement. Experiment with the different rotation styles here!
Given two points (both x and y coordinates), glide the sprite from one location to the other before calculating the slope (and printing this value). The formula for a slope is (Y2-Y1)/(X2-X1)
Create an arrow-key game that allows you to move the sprite around the screen. Include a A-D control system that allows you to rotate both left and right with the sprite. 
New England is on the boundary between deciduous forest (like oak trees) and coniferous forest (pine trees). Create an imaginary boundary down the y-axis. If your WASD controlled sprite is to the right of this boundary, it will print out “coniferous territory.” Otherwise, it will print out “deciduous” territory. This will simulate the real world. (Hint: You will need to use the x-position data block to determine whether the sprite is to the left or right of the y-axis)

Conditional Statements in Scratch

by 5:10 PM
Conditional or If-then relationships allow the computer to pick between two options. This kind of selection statement is extremely important.
 









If-then statements perform an action if the condition is true.  If-then-else statements perform an action if the condition is true and perform a different action if the condition is false


Boolean operators allow us to determine whether a condition is true or false. There are many kinds of boolean operators in Scratch. These diamond-shaped blocks will either return true or false


Comparison Boolean Operators (with Numbers): 



These blocks compare two numbers and
Return either true (when you have a valid
statement) or false (non-valid statement).

For example, 1 > 2 would return false and 2 > 1 would return true.

State whether the operator returns true or false:
(Write answers here)


Conditionals + Comparison Boolean Operators: These two block types can be put together to create if-then relationships with outputs. Please write the printed output (write “nothing” if there is no output) for the code sequences below. 























Boolean Logic: Boolean Logic allows us to combine two or more boolean operators to create more complicated conditions. Scratch supports three basic boolean logic blocks. 

AND Gate: Both inputs need to be “true” in order to return a “true”

OR Gate: One or both inputs needs to be “true” in order to return a “true”

NOT Gate: Automatically switch the value. True -> False | False -> True


Truth Tables: Boolean Logic can be represented by “truth tables.” These present all possible inputs and provide all possible outputs. 
Given: Truth Tables for OR (downward arrow), NOT (double-headed arrow), and AND (upward arrow) (in that respective order).





Comparison Boolean Operators (with Strings): We have a boolean operator that can check for letters in a string.
Write an answer here.


Keyboard Sensing: You can also create controls based on keyboard booleans which check whether a key is pressed (true result) or not pressed (false result).



What prints when I press “w”:

What prints when I press “a”:

What prints when I press “s”:

What prints when I press “d”:

The “forever” loop: This allows us to keep checking for different conditions and seeing if they are true. Without the forever loop, the flow of control (sequence of code) would run once and be done. This would be very quick, and we wouldn’t be able to press a key in time


Exercises:

Create a variable, set it to a random number 1-3 and use comparison boolean operators and conditionals to print out a color associated with that number (you may select these combinations yourself).

Search the string “I love Scratch” for the letter “s” with an if-then-else statement. Utilize printing to see whether the letter was found. 

Write a calculator script, taking in three user inputs (two numbers and the operation denoted by a sign +, -, *, /) and then printing out the solution to the problem based on the given sign. 

Initialize (a.k.a. create) a variable to represent a number line. Write a program that continuously (i.e. surrounded by a for loop) allows me to either move up (+1) or down (-1) a number line (represented by the var #).

What is the result of these (try them out!):
(3>2)AND(4<2):
(3>2)OR(4<2):
NOT((3>2)AND(4<2)):
NOT((3>2)OR(4<2)):

Advanced: In chemistry, hydrogen bonds only occur when in elements that contain both hydrogen (H) and nitrogen (N), both hydrogen (H) and oxygen (O), or both hydrogen (H) and fluorine (F). Given two compounds through user input, print whether they will be able to form hydrogen bonds. This can only occur if they both meet the conditions stated before (having both H and N, H and O, or H and F).


Powered by Blogger.