Vocabulary
Gotta know vocabulary words for units 2 and 3
Unit 2 Binary/Data Terms
Bits: The smallest unit of computational storage. Stores a boolean value and can be either on or off, 1 or 0.
Bytes: A collection of 8 bits, typically, characters are encoded with a binary byte, such as the ascii encoding system
- Nibble: A collection of 4 bits, can store a value between 0 and 15. Due to this nature, a nibble could also be stored within one hexadecimal digit.
Hexadecimal: The base 16 numbering system. Follows the standard base 10 digits from 0 - 9, and then branches off. In hex, 10 is represented as A, 11 is represented as B and so on until F, which represents 15.
Binary Numbers:
The binary representation of a number. Stored in bits of powers of two. If a bit's value is 1, that means that that power of two "fits within the original number. If the bit is 0, that means that that number does not fit within the original number.
Unsigned Integer:An integer value without a specified sign. In other words, these integers are always positive or 0. An unsigned int has 32 bits to store a value that can range from 0 to 4,294,967,295 (2^32 - 1)
Signed Integer: An integer value with a specified sign. In other words, these integers can be either positive or negative. A signed int also has 32 bits to store a value that can range from -2,147,483,647 (-2^31 + 1) to 2,147,483,647 (2^31 - 1)
Floating Point: A floating point number is a number that contains a decimal point, or some decimal value attached to the number itself. A floating point number typically also consists of 32 bits. In memory, the floating point number is stored with 1 bit for the sign of the number, 8 bits for the exponent, and 23 bits fo the fraction. This type of floating point number is called "Single precision".
Binary Data Abstraction
The act of taking higher level data and simplifying it through a binary representation of it. EG, color and sound could be broken into numerical values, then decimal representations.
Boolean:A boolean value is one that could be either on or off. Typically, boolean values are represented in programing as either True or False.
print("A quick demonstration on the behaviors of booleans and their operations")
t = True
f = False
print(t == f)
print(t != f)
print(not t)
print(t)
print(f)
ASCII: A character encoding system based on binary that coordinates letters, special characters, and certain control characters.
Unicode: Another character encoding system that uses 16 bits instead of 8 bits to encode characters. Thus, unlike ASCII, Unicode is able to store much more characters on a broader scale.
RGB: A color model in which the colors red, blue and green are mixed together in order to form different blends and hues of colors.
Data Compression
The act of of restructuring or encoding text in an attempt to reduce the overall size of a particular file or string.
Lossy:An irreversible form of data compression that uses imprecise rounding and approximations to reduce data size. Some examples are JPEG image, MPEG video and MP3 audio formats. Lossless: In the name, when re-extracting or recovering, the original data can almost be perfectly restored from the compression, hence lossless. This type of compression is possible because of various statistical redundancies that occur in files and data.
var_int = 1337
var_bool = True
var_string = "I love coding"
print("Integer Variable: ", var_int)
print("Boolean Variable: ", var_bool)
print("String Variable: ", var_string)
Data Types: A specific family or group of similar data that grant certain interactions or interpretations of it's data. Common examples are:
- Integer
- Float
- Character
- Boolean
- String
- Array
- Enums
Assignment Operators: Assignment operators are operators that can perform a certain arithmetic operation, while assigning a value to a certain variable.
x = 10
print("x = ", x)
x += 40
print("x = ", x)
x *= 60
print("x = ", x)
x /= 3
print("x = ", x)
x -= 25
print("x = ", x)
x %= 23
print("x = ", x)
Managing Complexity with Variables
Variables can be used to create references to values and complex structures in our code
Lists:A python list is a data structure that allows for the storage of multiple values sequentially within a single variable. A list is also one of python's iterables, which are objects that could be traversed via iteration
.
2D-Lists: 2-Dimensional lists are essentially lists that have nested lists inside them, hence, two dimensional. in this case, the nested list would count as one whole element of the larger list, and can have it's own elements to be accessed.
Dictionaries: Dictionaries in python are similar to hashmaps in C++ and other languages. Dictionaries serve to store key-value pairs, which is convenient for matching one value to another.
Class: A class is one of the fundamental building blocks for Object Oriented Programming
. A class serves as a blueprint for an Object
, which can contain various attributes and methods.
arr1 = [1,2,3,4,5,6,7,8,9,10]
# List operations
x = arr1[1] # retrieving the second element
y = arr1.pop() # popping and storing the last element of hte list within variable y
arr1.insert(3,4) # inserting value 4 at index 3 of the list
arr1.append(11) # Adding 11 at the end of the list
print("A python list: ", arr1)
# Python's list comprehension syntax
arr2 = [i+i-1 for i in range(1,11)] # Creating a list of the first 10 odd numbers
print("First 10 odd numbers: ", arr2)
# Dictionaries
names = {
"Alex":16,
"Evan":17,
"Hasseb":15,
"Nathan":17,
"Lily":16
}
print(names["Alex"]) # Accessing the value of Alex
for key in names.keys(): # Accessing each element in the dictionary
print(key + " : " + str(names[key]) + " years old")
# Classes
class Vehicle():
def __init__(self, color="white", speed=0.2): # Class Constructor
self.color = color # Class Attributes
self.speed = speed
self.pos = 0
self.time = 60
def goForward(self): # Class Methods
self.pos + self.speed * 60
def goBackwards(self):
self.pos - self.speed * 60
class Car(Vehicle): # Child class inheriting from the vehicle class
def __init__(self, color = "red", speed = "0.8"):
self.fuel = 45
def getSpeed(self):
print(self.speed)
def getFuel(self):
print(self.fuel)
car1 = Car()
car1.getSpeed()
Expressions: A combination of operators and terms that form a mathematical relationship.
Comparison Operators: Compares two values and returns a boolean result.
Booleans Expressions and Selection: An expression that would return a boolean value, either True or False. If True, the program will select that value and do something with it, if not, the program will ignore that value
Booleans Expressions and Iteration: Similar to "Boolean Expressions and Selection" (see above), except boolean expressions could be used as conditionals within loop and iterations to create logical progressions.
Truth Tables: A set of rules for binary operations that are always strictly true:
res = 1+5*9/2+6
print(res)
# Comparison Operators
print(6>1)
print(6<1)
print(42>=3)
print(2349<=34)
print(18==18)
print(81!=81)
# Boolean Expressions and selection
arr1 = [123,13,2,192,84,20,153,47,164]
arr2 = [i for i in arr1 if i > 100] # Checking each element in arr1 to see if they are greater than 100, if so, add to arr2
print(arr2)
# Boolean Expressions and iteration
i = 0
while i <= 10: # Checking for if the counter variable is smaller than or equal to 10.
print(i)
i+=1
Characters: A singular symbol or control character.
Strings: A collection of characters "stringed" together.
Length: The overall number of elements a particular structure has. Elements for a list, and characters for a string
Concatenation: The act of combining two strings together into a larger string
Upper and Lower: String operations in python to convert a string into either all caps or lower case. Useful for controlling case-insensitive user information.
Traversing strings: Strings can be traversed similar to lists, where we can visit each character and perform an action on it
a = "A"
# String:
b = "Hello World"
# Length
print(len(b)) # Length of the b string variable
# Upper and Lower
print(b.upper())
print(b.lower())
# Traversing a string
for i in b:
print(ord(i))
Conditional Statements
Python If, Elif, Else conditionals: The if statement in python consists of the if
keyword and a boolean condition. If the condition evaluates to be true, then the code underneath the if block would be executed.
The elif statement in python consists of the elif
keyword and another boolean condition. If the condition for the first if statement evaluates to be false, python will then check for the elif conditions in order. If any one of the conditions meet, python will execute the first True condition and stop the check there.
The else statement in python consists of the else
keyword and no conditions. The code under this block is ran if none of the if or elif statements are satisfied. Thus, the else statement could be thought of as a default output.
Nested Selection Statements: Similar to loops, if elif, and else statements could be nested within one another to create more specific and complex checks.
temp = 75
if temp <= 80:
if temp >= 60:
print("It is warm outside, Go play!")
elif (temp < 60 and temp > 35):
print("It is slightly chilly, go wear a jacket!")
else:
print("Prepare for snow!")
elif (temp > 80 and temp < 100):
print("It is pretty hot outside, bring some water")
else:
print("It is BURNING!!!!")
Python Iteration
Python For: A for loop is a loop used for iterating over an array of values or a range of numbers. Typically, a force loop could be used for traversing a list to perform actions on each element, or using numerical values to represent list indices.
While loops with Range with List: A while loop could be used in conjuncture with a range to specify a certain set of numbers to analyze. Typically, this set up could also be used with a list to traverse the list by indexes. A powerful aspect of this approach is that we can set different rules about how our range behaves to have traversing behaviors outside of the standard sequence.
Combining loops with conditionals to Break: An if-elif-else conditional could also be added within for and while loops to control code execution. A condition can be set such that if met, the program will call the break
keyword, which will automatically terminal the current iteration and end the loop cycle, continuing with the rest of the program.
Continue: The continue keyword can be used within a loop to skip all remaining code in that cycle and continue on to the next iteration.
arr = ["Bob", "John", "Alex", "Steve", "Michael"]
for i in range(5):
print(arr[i])
print("----------------------------------------")
# While loops with range with list
i = 0
while i in range(5):
print(arr[i])
i+=1
print("----------------------------------------")
# Combining loops with conditionals to Break:
for i in range(5):
if arr[i] == "Alex":
break
print(arr[i])
print("----------------------------------------")
# Continue keyword (We can skip an element)
for i in range(5):
if arr[i] == "Alex":
continue
print(arr[i])
Procedural Abstraction: Complex operations and computing logic could be stored within smaller procedures that when combined, make up the whole program and logic. These smaller bits of code allows for a simpler view of the code and better code structure.
Python Def procedures: Procedures (functions) could be created in python using the def
keyword
Parameters: Parameters are the input values for a given procedure or function
Return Values: Return values are the result of each procedure or the desired value that the given procedure passes on to the rest of the program
def fibo(n): # Procedural Abstraction by abstracting the fibonacci sequence with the python def function
if n <= 2: # n is our argument
return 1
return fibo(n - 1) + fibo(n - 2) # Our return values are either a) 1 if the number is equal to or smaller than 2
# or b) the sum of the 2 previous fibonacci numbers
print(fibo(10))