Unit 2

Bits

A bit (binary digit) is the smallest unit of data that a computer can process and store. A bit is always in one of two physical states, similar to an on/off light switch. The state is represented by a single binary value, usually a 0 or 1.

Bytes

In most computer systems, a byte is a unit of data that is eight binary digits long. A byte is the unit most computers use to represent a character such as a letter, number or typographic symbol. Each byte can hold a string of bits that need to be used in a larger unit for application purposes.

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.

In computing and digital technology, a nibble is four consecutive binary digits or half of an 8-bit byte. When referring to a byte, it is either the first four bits or the last four bits, which is why a nibble is sometimes referred to as a half-byte.

Binary Numbers:

Unsigned Integer

Unsigned Integers (often called "units") are just like integers (whole numbers) but have the property that they don't have a + or - sign associated with them. Thus they are always non-negative (zero or positive). We use uint's when we know the value we are counting will always be non-negative.

Signed Integer

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.

Floating Point

A floating point number, is a positive or negative whole number with a decimal point. For example, 5.5, 0.25, and -103.342 are all floating point numbers, while 91, and 0 are not. Floating point numbers get their name from the way the decimal point can "float" to any position necessary.

Binary Data Abstractions:

Boolean

A data type that has one of two possible values which is intended to represent the two truth values of logic and Boolean algebra.

Unicode/ASCII

Unicode and ASCII are the most popular character encoding standards that are currently being used all over the world. Unicode is the universal character encoding used to process, store and facilitate the interchange of text data in any language while ASCII is used for the representation of text such as symbols, letters, digits, etc. in computers.

RGB

Colors in a computer program are represented by combining 3 "pigments". These pigments are Red, Green, and Blue (which contrasts with the "primary" colors we are used to as a child). By combining some amount of Red, some amount of Green, and some amount of Blue, any (displayable) color can be achieved.

Variables

A variable is a value that can change, depending on conditions or on information passed to the program. Typically, a program consists of instruction s that tell the computer what to do and data that the program uses when it is running.

Data Types

A data type is a classification of data which tells the compiler or interpreter how the programmer intends to use the data. Most programming languages support various types of data, including integer, real, character or string, and Boolean.

Assignment Operators

Assignment operators are used to assign values to variables.

Lists

A list is a sequence of several variables, grouped together under a single name. Instead of writing a program with many variables x0 , x1 , x2 , … you can define a single variable x and access its members x[0] , x[1] , x[2] , etc.

2D Lists

A 2D array in python is a two-dimensional data structure stored linearly in the memory. It means that it has two dimensions, the rows, and the columns, and thus it also represents a matrix.

Dictionaries

A dictionary is also called a hash, a map, a hashmap in different programming languages. The keys in a dictionary must be simple types (such as integers or strings) while the values can be of any type. Different languages enforce different type restrictions on keys and values in a dictionary.

Class

In object-oriented programming , a class is a template definition of the method s and variable s in a particular kind of object . Thus, an object is a specific instance of a class; it contains real values instead of variables. The class is one of the defining ideas of object-oriented programming.

Algorithms

A programming algorithm is a procedure or formula used for solving a problem. It is based on conducting a sequence of specified actions in which these actions describe how to do something, and your computer will do it exactly that way every time. An algorithm works by following a procedure, made up of inputs.

Sequence

In programming, sequence is a basic algorithm: A set of logical steps carried out in order. Computers need instructions in the form of an algorithm in order to complete a desired task, and this algorithm must have the correct order of steps, or sequence.

Selection

Selection is a programming construct where a section of code is run only if a condition is met. In programming, there are occasions when a decision needs to be made. Selection is the process of making a decision. The result of the decision determines which path the program will take next.

Iteration

In programming specifically, iterative refers to a sequence of instructions or code being repeated until a specific end result is achieved. Iterative development is sometimes called circular or evolutionary development.

Expressions

In programming language terminology, an “expression” is a combination of values and functions that are combined and interpreted by the compiler to create a new value, as opposed to a “statement” which is just a standalone unit of execution and doesn't return anything.

Comparison Operators

Comparison operators can compare numbers or strings and perform evaluations. Expressions that use comparison operators do not return a number value as do arithmetic expressions. Comparison expressions return either 1 , which represents true, or 0 , which represents false.

Truth Tables

A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.

Characters

The character in computer programming is an essential category of variable or constant that is defined and dealt with in code.

Strings

A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).

Length

It takes a string as a parameter and returns an integer as the length of that string.

Concatenation

Concatenation, in the context of programming, is the operation of joining two strings together. The term "concatenation" literally means to merge two things together.

Upper

The upper() method converts all lowercase characters in a string into uppercase characters and returns it.

Lower

The lower() method returns a string where all characters are lower case. Symbols and Numbers are ignored.

Traversing Strings

For strings this means that we would like to process one character at a time. Often we start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal.

Python If

If statements are logical blocks used within programming. They're conditional statements that tell a computer what to do with certain information. In other words, they let a program make 'decisions' while it's running. They're comprised of a minimum of two parts, 'if' and 'then'.

Elif

In Python, 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.

Else conditionals

Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

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.

Python For

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.

While loops with Range

It can. You never change the value of x so it's always in the range. What does "use a while loop on a range" even mean? If it means "iterate over the range", then the answer is "because that's what for loops are for".

While loops with List

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.

Combining loops with conditionals to Break

Within the for loop, there is an if statement that presents the condition that if the variable number is equivalent to the integer 5, then the loop will break. Within the loop is also a print() statement that will execute with each iteration of the for loop until the loop breaks, since it is after the break statement.

Continue

Break statement stops the entire process of the loop. Continue statement only stops the current iteration of the loop. Break also terminates the remaining iterations. Continue doesn't terminate the next iterations; it resumes with the successive iterations.

Procedural Abstraction

Procedural abstraction is when we write code sections which are generalised by having variable parameters. The idea is that we have code which can cope with a variety of different situations, depending on how its parameters are set when it is called.

Python Def procedures

A Function is a series of Python statements begins by a def , followed by the function name and enclosed in parenthesis. A Function may or may not return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure).

Parameters

A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions. For example: function example(parameter) { console.

Return Values

A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string. The type of value your function returns depends largely on the task it performs.

Code Examples

num1 = 15
num2 = 25
num3 = 42
num2 = num3
num3 = num1
num1 = num2

print(num1)
print(num2)
print(num3)
42
42
15
num2 += num1
print(num1)
print(num2)

print(str(num1)+ str(num2))
print(num1 + num2)
42
84
4284
126
colorsList=["pink", "yellow", "green", "blue", "orange"]

print(colorsList)

colorsList=[] # can be used if you want to create a list that can be filled with values later

# copy of the list is made; the list isn't sorted in place
def Reverse(lst): # defining variable: lst 
    new_lst = lst[::-1] 
    return new_lst
 
lst = ["pink", "green", "purple", "yellow", "orange", "blue", "black"]
print(Reverse(lst)) # reverse 1st
['pink', 'yellow', 'green', 'blue', 'orange']
['black', 'blue', 'orange', 'yellow', 'purple', 'green', 'pink']
questions = 3
correct = 0

# Use a dictionary for the questions
quesList = ["To be or not to be?", "What's your name?", "How was break?", "Is this homework?"]

# Use a dictionary for the correct solutions
soluList = ["idk", "mani", "fine", "yea"]

for i in quesList:
    print(i)
    
value1 = input ("Q1")
value2 = input ("Q2")
value3 = input ("Q3")
value4 = input ("Q4")

for n in soluList: 
    if value1 == n:
        correct += 1
        
for x in soluList: 
    if value2 == x:
        correct += 1
    
for z in soluList: 
    if value3 == z:
        correct += 1
    
for y in soluList: 
    if value4 == y:
        correct += 1

print("Final score: " + str(correct))
To be or not to be?
What's your name?
How was break?
Is this homework?
Final score: 4
Num1 = 10
Num2 = Num1 % 3 * 4
Num1 = Num2
Num3 = Num1 * 3
Result = Num3 % 2
print(Result)
0
type = "curly"
color = "brown"
length = "short"
type = "straight"
hair = type + color + length
print(hair)
straightbrownshort
sports = ["football", "soccer", "baseball", "basketball"]
index = 0
# change the value "soccer" to "hockey"
sports.remove(sports[index])
sports.insert(0, "hockey")
print(sports)
['hockey', 'soccer', 'baseball', 'basketball']
words = ["alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliett", "kilo",
"lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray", "yankee", "zulu"]

index = 0
inp = input().lower()
def show_letters(inp):
    for letter in inp:
        for let in words:
            if letter == let[index]:
                print(let)
show_letters(inp)
bravo
alfa
tango
mike
alfa
november
keypad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [" ", 0, " "]]

def print_matrix3(matrix):
    for a in matrix:
        itr = iter(a)
        print(next(itr), next(itr), next(itr))
        
print_matrix3(keypad)
1 2 3
4 5 6
7 8 9
  0  
letters = [["`", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "-", "="],
            ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]"],
            ["A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'"],
            ["Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"]]

letters_lower1 = [letter.lower() for letter in letters[1]]               # additional lines of code for better capitalization
letters_lower2 = [letter.lower() for letter in letters[2]]
letters_lower3 = [letter.lower() for letter in letters[3]]

print(letters[3][6] + letters_lower2[0] + letters_lower3[5] + letters_lower1[7])
print(letters[3][6] + letters_lower2[0] + letters_lower1[5])
print(letters[0][9] + letters[0][9])
Mani
May
18
print("100 == 100:",100==100)
print("Hello == Adios:","greeting"=="farewell")
print("Hello != Adios:","greeting"!="farewell")
print("Hello == Hola:","greeting"=="greeting")
print("5>=4:", 5>=4)
print ('')

# Notice that relational operators can even work on lists!
# For lists, the relational operator compares each respective component until an answer is derived

print("['a','b','c'] > ['x','y','z']:", ['a','b','c'] > ['x','y','z'])
print("[1,2,3,5] > [1,2,3,4]:", [1,2,3,5] > [1,2,3,4])
print("[1,2,3,5] < [1,2,3,4]:", [1,2,3,5] < [1,2,3,4])
print("[1,2,3,5] == [1,2,3,4]:", [1,2,3,5] == [1,2,3,4])
100 == 100: True
Hello == Adios: False
Hello != Adios: True
Hello == Hola: True
5>=4: True

['a','b','c'] > ['x','y','z']: False
[1,2,3,5] > [1,2,3,4]: True
[1,2,3,5] < [1,2,3,4]: False
[1,2,3,5] == [1,2,3,4]: False
print("1 > 2 or 5 < 12:", 1 > 2 or 5 < 12)
# Output TRUE  using OR ^


# Output FALSE using NOT
print("24 > 8:", not 24 > 8)

# Output FALSE using AND
print("10 > 20:", 10 > 20 and False)
1 > 2 or 5 < 12: True
24 > 8: False
10 > 20: False
cost = 30
stat = 1       
if stat < 1:
    print("this product is no good") 
else:
    if cost > 50 and stat == 1:
        print("this product is too expensive") 
    else:
        if 50 > cost > 25 and stat == 1:
            print("this is a regular product")
        else:
            print("this is a cheap product")
this is a regular product
questions = {
    "Which movie is a comedy?":["a. The King's Man","b. What's eating Gilbert Grape", "c. About Time", "d. Batman"], 
    "Which movie features 50 Cent?":["a. Shaft", "b. 8 Mile","c. Southpaw", "d. Batman"], 
    "Who is the best Batman?":["a. Christian Bale","b. Ben Affleck", "c. Robert Pattinson", "d. Kevin Conroy"]
    }

answers = {
    "Which movie is a comedy?":"c", 
    "Which movie features 50 Cent?":"c", 
    "Who is the best Batman?":"d"
    }

score = 0

print("Ready for a movie quiz?")

for q,a in questions.items():

    print(q)
    print(*a)

    inp = input("Enter Your Answer")

    if(answers.get(q)==inp):
        score = score +1
    else:
        print("SYNTAX ERROR...jk try again")
        break

print('Final Score:', score)  
Ready for a movie quiz?
Which movie is a comedy?
a. The King's Man b. What's eating Gilbert Grape c. About Time d. Batman
Which movie features 50 Cent?
a. Shaft b. 8 Mile c. Southpaw d. Batman
Who is the best Batman?
a. Christian Bale b. Ben Affleck c. Robert Pattinson d. Kevin Conroy
Final Score: 3
import random       # module for generating random item from a list

nums = list(range(1, 21))       # list of numbers

num1 = int(random.choice(nums))     # int takes the integer, random utilizes the module
num2 = int(random.choice(nums))     # the three numbers are generated here
num3 = int(random.choice(nums))

def end():          # procedure for endgame 
    print("Okay I guess")

rd = input("Are you ready? y/n")        # useless prompt to initiate the game       

if rd == "y":  
    print(num1)
    print("continue?y/n")       # basically a checkpoint
    cn = input()
    if cn == "y":
        print(num2)
        print("continue?y/n")
        cn2 = input()
        if cn2 == "y":
            print(num3)
            if num1 > num2 and num1 > num3:         # checks if num1 is the greatest
                print("Your Score:" , num1)
            else:
                if num2 > num1 and num2 > num3:         # checks if num2 is the greatest
                    print("Your Score:" , num2)
                else:
                    if num3 > num1 and num3 > num2:         # checks if num3 is the greatest
                        print("Your Score:" , num3)
        else:
            end()
    else:
        end()
else:
    end()
4
continue?y/n
18
continue?y/n
8
Your Score: 18