Unit 2… Binary/Data Terms

  • bits: the minimum unit of binary information stored in a computer system. A bit can have only two states, on or off, which are commonly represented as ones and zeros. In our binary markdown we used to change the number of bits.
  • bytes: A group of eight bits put together is known as a byte. A byte consists of 256 different combinations if you include the number 00000000 — all the binary numbers between 00000000 and 11111111.
  • hexadecimal/nibbles: Hexadecimal is a numbering system with base 16. It can be used to represent large numbers with fewer digits. In this system there are 16 symbols or possible digit values from 0 to 9, followed by six alphabetic characters -- A, B, C, D, E and F. For example, when we use Javascript to change the color of the background on our blogs, we use hexadecimals like #eb4034, which would give us a red color. Here's an example of it in our fastpages:

.post-content p, .post-content li { font-size: 20px; color: #515151; }

  • RGB- Hexadecimal is basically a short code for RGB color, they are simply different ways of communicating the same thing – a red, green, and blue color value. For example, (235, 64, 52) is the RGB for RED. Here's an example of how it is implemented in our fastpages:

a { color: rgb(255,255, 255) !important; }

  • boolean- value that is either true or false
x = 5
y = 4
z = 4 > 5
print(z) # value of z is false 
False
print(30 > 19) # Will output true, since is 30 is larger than 19

# Using variables and strings
a = "Yes"
b = "No"
print(a == b) # Will output false, not the same

# Renaming b
b = "Yes"
print(a == b) # Will output true, since both variables match
True
False
True

Unit 3… Algorithm/Programming Terms

  • variables- A variable is an abstraction inside a program that can hold a value. Each variable has associated data storage that represents one value at a time, but that value can be a list or other collection that in turn contains multiple values. Using meaningful variable names helps with readability of program code and understanding of what values are represented by the variables. Some programming languages provide types to represent data, which are referenced using variables.
  • data types- integer, string, float, boolean, lists, dictionaries, arrays, etc.
  • lists- Lists are used to store multiple items in a single variable.
  • dictionaries- A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.
x = 2 #integer
y = "school" #string
z = True #boolean
a = 2.7 #float
list = ["apple", "banana", "cherry"] #list
dict = {"name" : "John", "age" : 36} # dictionary
  • assignment operators:

A plus sign indicates addition: a + b

A subtraction sign indicates subtraction: a - b

An asterisk/star indicates multiplication: a * b

A slash indicates division: a / b

MOD represent the Modulus operator. Returns the value after division: a MOD b

result = 9 * 2 #multiplication operator 
print(result)
answer = 4-3 #subtraction operator 
print(answer)
18
1
  • algorithms- finite set of instructions that accomplish a specific task, composed of sequencing, selection, and iteration.
  • sequence- a section of code is run only if a condition is met. (ex: if statements)
  • selection- repeating steps or instructions over and over again (ex: loops)
  • iteration- outline or set of steps that we do and follow in order that they are given

Example: Set largestNumber to 0 Get next number in list If number is larger than largestNumber then set largestNumber to number If there are more numbers in list, go back to Step 2 Display largestNumber Sequencing: Steps 1-5 in order

Selection: Step 3

Iteration: Step 4

  • strings- a sequence of characters
  • concatenation- combines two or more strings into one
  • length- len function finds the number of characters in a string
  • substring- a part of a existing string

Ex: substring(“APCSPrinciples”, 3, 6)

Result: “CSPrin”

Starts at the 3rd character (“C”) and takes 6 characters after that (“SPrin), then in all (“CSPrin”)

stringExample = "this is an example of a string!" #strings are in quotations 
print(stringExample)
print(len(stringExample)) # this will find the number of characters in the string 
this is an example of a string!
31
age  = 17
print("I am", str(age), "years old.") #concatenation example, combining a string and integer together
str1 = "hello"
str2 = "there"
print(str1, str2) # putting the strings together 
I am 17 years old.
hello there
  • upper- upper() method returns the uppercase string from the given string. It converts all lowercase characters to uppercase.
  • lower- lower() method returns the lowercase string from the given string. It converts all uppercase characters to lowercase.
lowerCase = "this is all lowercase"
upperCase = "THIS IS ALL UPPERCASE"
print(lowerCase.upper()) # this will print the lower case in all upper case
print(upperCase.lower()) # this will print the upper case in all lower case 
THIS IS ALL LOWERCASE
this is all uppercase
  • comparison operators- Logical operators allow for boolean values to be evaluated. Pseudocode uses the logical operators NOT, AND, and OR.
print(1 == 1 and 10 >= 0) # Returns true because both statements are true

cookies = 25
brownies = 30
print("There is enough dessert") # First condition is false, but second condition is true
print(cookies == 50 or cookies + brownies >= 35) # Ends up returning true since at least one condition is true

# The expression "Blue" != "Green" is false
print(not "Blue" != "Green") # Not operator changes statement to not false, printing true
True
There is enough dessert
True
False
  • Truth tables- A truth table is a way of summarizing and checking the logic of a circuit. The table shows all possible combinations of inputs and, for each combination, the output that the circuit will produce.
    AND Operator
    Value 1 Value 2 Result
    1 1 1
    1 0 0
    0 1 0
    0 0 0
    OR Operator
    Value 1 Value 2 Result
    1 1 1
    1 0 1
    0 1 1
    0 0 0
    Not operator
    Not Value Result
    Not 1 0
    Not 0 1
  • if statement- will go through certain statements if the if expression is true
  • if-else- will go through a statement no matter what, but the statement which is run depends on the if expression is true or false
  • elif- elif is short for "else if" and is used when the first if statement isn't true, but you want to check for another condition. Meaning, if statements pair up with elif and else statements to perform a series of checks.
  • nested selection statements- Nested selection structures are used when more than one decision must be made before carrying out a task. Nesting is a programming activity, in which one program block is placed inside other program block of the same operation type. Nesting processes are mostly used implemented in the selection control structures.
S = 12
if S % 2 == 0:
    print(S)
else:
    print("This number is not even.")
12
number1 = 28
number2 = 43
def lessthan30(num):
    # Example of if statement
    if num < 30: # If this condition is true(variable is less than 30)
        print(num) # Then the value of the variable will be printed

lessthan30(number1) # The if statement is true, so it will print the value of 28
lessthan30(number2) # The if statement is false, nothing will be printed.
28
price = 100

if price > 100:
    print("price is greater than 100")
elif price == 100: #elif use 
    print("price is 100")
elif price < 100:
    print("price is less than 100")
price is 100
animals = ["lion", "tiger", "wildebeest", "shark", "jellyfish", "blobfish", "raven"]
 
print(animals)
for i in animals: # if else statement nested in for loop 
    if i == "shark": # What boolean value does this statement cause? Answer: True
        print("Fun Fact: The smallest shark is the dwarf lantern shark, and it is small enough to hold in your hand!")
    else:
        print(i)
['lion', 'tiger', 'wildebeest', 'shark', 'jellyfish', 'blobfish', 'raven']
lion
tiger
wildebeest
Fun Fact: The smallest shark is the dwarf lantern shark, and it is small enough to hold in your hand!
jellyfish
blobfish
raven
  • For Loop: repeats a function for a set number of times; I is the number of times repeated. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
  • While Loop: the while loop is used to repeat a section of code an unknown number of times until a specific condition is met. A while loop will execute a set of statements as long as a condition is true.
  • return values: The value that a function returns to the caller is generally known as the function's return value. All Python functions have a return value, either explicit or implicit.
  • continue: With the continue statement we can stop the current iteration, and continue with the next:
fruits = ["apple", "banana", "cherry"]
for x in fruits: # loops through the entire list 
  print(x)
apple
banana
cherry
i = 1
while i < 6:
  print(i) # i will keep printing as long as the statement is true 
  i += 1
1
2
3
4
5
i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)
1
2
4
5
6
def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
15
25
  • range: The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
x = range(3, 6)
for n in x:
  print(n)
3
4
5
  • class- A class creates a new local namespace where all its attributes are defined. Attributes may be data or functions. Like function definitions begin with the def keyword in Python, class definitions begin with a class keyword.
  • parameters- Parameters are the variables that appear between the brackets in the "def" line of a Python function definition. Parameters are input values of a procedure.
  • Procedure: is a named group of programming instructions that may have parameters and return values. Procedures can be reffered to as method or function depending on the programing language. A procedrure call interrupts an execution of statements and makes the program execute the statements in the procedure.
    • There are two types of procedures, one that returns a value or some type of data and on that just executes a block of statements
  • Modularity - the practice of breaking a complex program into smaller, independent parts or modules that can be used and reused in different parts of the program
  • procedural abstraction- One good use of a procedure is to eliminate duplicate code. In addition to improving the readability of the app, the use of a procedure will make it easier to modify that chunk of code because it only occurs once in the program. Use of parameters and complexity.
    • which provides a name for a process and allows a procedure to be only knowing what it doe,not how it does it.
class Person:
    "This is a person class"
    age = 10

    def greet(self):  #parameters 
        print('Hello')

# Output: 10
print(Person.age)
10
  • simulation: A simulation is an simpler abstraction of an very complicated natural phenomena. It removes details that are unnecessary or are too difficult to simulate. The level of abstraction in a simulation depends on why we're creating it in the first place.
    • why we use? safer, repeatable, less expensive, can make predictions
  • A problem is a description of a task that may or may not be able to be solved through the use of an algorithm. An instance of a problem includes a specific input. One example of this type of problem is a sorting problem.
  • A decision problem is a problem with a binary answer (yes or no). An optimization problem is a problem with the objective of finding the BEST solution amongst many possibilities to solve a problem.
  • An algorithm's efficiency is determine through formal or mathematical reasoning.
  • undecidable problem- problems for which no algorithms can be built that can provide a correct yes or no answer or a solution
  • decidable problem- problems for which algorithms could be written to solve/produce a correct output for all inputs.
number = 20  #set number equal to random value 
if number > 10: # if the number is greater than 10 
    print("greater than 10") #print 
else: # if less than 10 
    print("not greater than 10") # print
greater than 10
num = 1
while num == 0: # the number will never equal 0 since we set it to 1, so this is undecidable
  print(num)
  num = num + 1
  • A recursion is when a function calls itself until someone stops it. If no one stops it then it'll recurse (call itself) forever. Recursive functions let you perform a unit of work multiple times. This would be much more efficient and faster than the code above because, there is much less code and you don't need to keep calling the function, it will just do it automatically.
def tri_recursion(k):
  if(k>0):
    result = k+tri_recursion(k-1)
    print(result)
  else:
    result = 0
  return result

print("Recursion Example Results")
tri_recursion(6)
Recursion Example Results
1
3
6
10
15
21
21
import random

print("Welcome to a coin flip simulation!")
print("----------------------------------")

n = 10000 #this value can easily be changed to change the sample size
heads = 0
tails = 0
 
for i in range(n):
    flip = random.randint(1,2) # get a random number between 1 and 2
    if flip == 1: # head
        heads = heads + 1
    else:         # tail
        tails = tails + 1
 
print('Number of heads:', heads)
print('Number of tails:', tails)
Welcome to a coin flip simulation!
----------------------------------
Number of heads: 5048
Number of tails: 4952