Unit 2

Bits, Bytes, Hexadecimal / Nibbles: A bit is a unit of information that can have two values, typically represented as a 0 or a 1. A byte is a unit of digital information that typically consists of eight bits. Hexadecimal, or "hex" for short, is a numbering system that uses 16 different digits, represented as the numbers 0 through 9 and the letters A through F. Each hexadecimal digit represents four binary digits, also known as a nibble. In other words, two hexadecimal digits can be used to represent one byte. Hexadecimal numbers are often used to represent large binary values in a more compact and human-readable form.

value = 0b1011

# Print the value of the first bit
print(f"First bit: {value & 0b1}")

# Print the value of the second bit
print(f"Second bit: {value & 0b10}")

# Print the value of the third bit
print(f"Third bit: {value & 0b100}")

# Print the value of the fourth bit
print(f"Fourth bit: {value & 0b1000}")
First bit: 1
Second bit: 2
Third bit: 0
Fourth bit: 8

Binary Numbers: Unsigned Integer, Signed Integer, Floating Point: A binary number is a number expressed in the base-2 numeral system, which uses only two digits: 0 and 1. This is different from the base-10 numeral system, which uses the digits 0 through 9. In computer science, binary numbers are often used to represent values in a computer's memory or to represent data being transmitted between computer systems.

value = 0b1001

# Print the value of the variable in decimal
print(f"Value in decimal: {value}")

# Print the value of the variable in binary
print(f"Value in binary: {bin(value)}")
Value in decimal: 9
Value in binary: 0b1001

Binary Data Abstractions: Boolean, ASCII, Unicode, RGB:

  • Boolean data type is a binary data type that can have only two possible values: true or false. It is often used to represent a binary decision or a simple true/false choice in a program.
  • ASCII encodes characters as numbers. It represents each character with a unique integer value between 0 and 127. ASCII is a 7-bit encoding, which means that it uses 7 bits to represent each character.
  • Unicode is a standard for encoding characters that includes a much larger range of characters than ASCII. It represents each character with a unique integer value, which can be up to 21 bits in length. Unicode includes all the characters in ASCII, as well as many additional characters from a variety of scripts and languages.
  • RGB (Red Green Blue) is a color model used to represent colors on a computer or other digital display device. In the RGB model, each color is represented by a combination of red, green, and blue light. The intensity of each color is represented by a number between 0 and 255, with 0 representing no intensity and 255 representing full intensity.
# Create list of phonetic alpabets

words = ["alfa", "beta", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "julitt", "kilo", "lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "wiskey", "xray", "yankee", "zulu"]


# Get ASCII value of char 'a'

ascii_a = ord('a');


# Get input from terminal

print("Please type in a word (alphabets ONLY) ...")

in_string = input()



# Convert the input string into all lower case

in_string = in_string.lower()

print(in_string + " ->" + "\n")


# Find ASCII value of each "char" in the "string"

# The difference of ASCII value between these characters and "a"

# will become the index to the list of words


for k in range(len(in_string)) :

     in_ascii = ord(in_string[k]) - ascii_a

     print(words[in_ascii])
Please type in a word (alphabets ONLY) ...
mortensen ->

mike
oscar
romeo
tango
echo
november
sierra
echo
november
# Define a string with Unicode characters
unicode_string = "Hi, my name is Max"

# Print the string to the console
print(unicode_string)

# Get the length of the string
string_length = len(unicode_string)
print(f"The length of the string is {string_length} characters.")

# Get the Unicode code point for the first character in the string
first_char_code = ord(unicode_string[0])
print(f"The Unicode code point for the first character is {first_char_code}.")

# Convert the Unicode code point to a character
first_char = chr(first_char_code)
print(f"The character for code point {first_char_code} is {first_char}.")
Hi, my name is Max
The length of the string is 18 characters.
The Unicode code point for the first character is 72.
The character for code point 72 is H.
# Define a color using RGB values
red = (255, 0, 0)

# Print the RGB values to the console
print(f"Red: {red[0]}")
print(f"Green: {red[1]}")
print(f"Blue: {red[2]}")

# Convert the RGB values to a hexadecimal string
hex_string = "#{:02x}{:02x}{:02x}".format(red[0], red[1], red[2])
print(f"Hexadecimal: {hex_string}")

# Define a function to convert an RGB tuple to a hexadecimal string
def rgb_to_hex(rgb):
    return "#{:02x}{:02x}{:02x}".format(rgb[0], rgb[1], rgb[2])

# Convert the RGB values to a hexadecimal string using the function
hex_string = rgb_to_hex(red)
print(f"Hexadecimal: {hex_string}")
Red: 255
Green: 0
Blue: 0
Hexadecimal: #ff0000
Hexadecimal: #ff0000

Data Compression: Lossy, LosslessL: Not discussed yet

 

Unit 3

Variables, Data Types, Assignment Operators:

  • A variable is a named location in a computer's memory where a value can be stored and retrieved. In most programming languages, variables have a specific data type, which determines the kind of values that the variable can store.

  • Data types are categories that are used to classify the different types of data that can be stored in a variable. Examples of common data types include integers, which are whole numbers, and strings, which are sequences of characters.

  • Assignment operators are operators that are used to assign a value to a variable. In most programming languages, the assignment operator is the equal sign (=). For example, the following code uses the assignment operator to assign the value 10 to a variable named x:

x = 10

Once this code is executed, the value 10 will be stored in the variable x, and we can use the variable to access this value later in the program. For example, we could print the value of x using the following code:

print(x)  # Output: 10

It is important to note that the assignment operator is different from the equality operator (==), which is used to compare two values for equality. For example, the following code uses the equality operator to check whether the value of x is equal to 10:

if x == 10:
    print("x is equal to 10")

In this case, the code will print the message "x is equal to 10" because the value of x is indeed equal to 10.

Managing Complexity with Variables: Lists, 2D Lists, Dictionaries, Class: Managing complexity with variables involves using different data structures to organize and manipulate data in a way that makes it easier to understand and work with. Some common data structures for managing complexity include lists, 2D lists, dictionaries, and classes.

A list is an ordered collection of values that can be of any data type. In most programming languages, lists are enclosed in square brackets ([]) and the values within a list are separated by commas. For example, the following code defines a list of three strings:

names = ["Alice", "Bob", "Charlie"]

A 2D list, also known as a two-dimensional array or matrix, is a list of lists. It is a data structure that allows us to store and manipulate data in a grid-like format. For example, the following code defines a 2D list with three rows and four columns:

grid = [    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

A dictionary is a data structure that maps keys to values. In most programming languages, dictionaries are enclosed in curly braces ({}) and the keys and values within a dictionary are separated by colons. For example, the following code defines a dictionary that maps strings to integers:

ages = {
    "Alice": 25,
    "Bob": 30,
    "Charlie": 35
}

A class is a blueprint for creating objects. In object-oriented programming, a class defines the attributes and behaviors of a particular type of object. For example, the following code defines a class named Person with two attributes (name and age) and one behavior (a method named greet() that prints a greeting message):

A class is a blueprint for creating objects. In object-oriented programming, a class defines the attributes and behaviors of a particular type of object. For example, the following code defines a class named Person with two attributes (name and age) and one behavior (a method named greet() that prints a greeting message):

These data structures can be used to manage the complexity of data by organizing it in a way that makes it easier to understand and work with. For example, we could use a list to store a collection of strings, a 2D list to store a grid of numbers, a dictionary to store a mapping of keys to values, or a class to define the attributes and behaviors of a particular type of object.

Algorithms, Sequence, Selection, Iteration:

  • An algorithm is a set of steps or procedures for solving a specific problem. It is a step-by-step approach to achieving a desired result.

  • A sequence is a series of steps or events that occur in a specific order. In programming, a sequence can refer to the order in which statements or blocks of code are executed.

  • Selection is the process of choosing between different options or paths based on certain conditions. In programming, selection is often implemented using control structures such as if statements or switch statements, which allow the program to execute different code blocks depending on whether a certain condition is met.

  • Iteration is the process of repeating a set of steps or instructions multiple times. In programming, iteration is often implemented using looping structures such as for loops or while loops, which allow the program to execute a block of code multiple times until a certain condition is met.

# Define a function to find the largest number in a list
def find_largest(numbers):
  # Set the initial largest number to the first number in the list
  largest = numbers[0]
  
  # Iterate through the rest of the numbers in the list
  for number in numbers[1:]:
    # If the current number is larger than the current largest number, update the largest number
    if number > largest:
      largest = number
      
  # Return the largest number
  return largest

# Test the function with a list of numbers
numbers = [1, 3, 2, 5, 4]
largest = find_largest(numbers)
print(f"The largest number is {largest}.")
The largest number is 5.

Expressions, Comparison Operators, Booleans Expressions and Selection, Booleans Expressions and Iteration, Truth Tables:

  • An expression is a combination of values, variables, and operators that produces a result when evaluated. Expressions can be used to perform calculations or to return a value.

  • Comparison operators are operators that compare two values and return a Boolean value indicating whether the comparison is true or false. Some common comparison operators in Python are:

==: equal to !=: not equal to

:greater than<: less than =:greater than or equal to<=: less than or equal to

  • Boolean expressions are expressions that evaluate to a Boolean value of True or False. They can be created using comparison operators or by combining other Boolean expressions using logical operators such as and, or, and not.
  • Selection refers to the process of choosing between different options or paths based on certain conditions. In programming, selection is often implemented using control structures such as if statements or switch statements, which allow the program to execute different code blocks depending on whether a certain condition is met. Boolean expressions can be used in selection to determine which code block to execute based on the truth value of the expression.

  • Iteration is the process of repeating a set of steps or instructions multiple times. In programming, iteration is often implemented using looping structures such as for loops or while loops, which allow the program to execute a block of code multiple times until a certain condition is met. Boolean expressions can be used in iteration to control the execution of the loop by determining when to terminate the loop based on the truth value of the expression.

  • A truth table is a chart that lists all possible combinations of input values for a logical function and shows the corresponding output value for each combination. Truth tables can be used to help understand the behavior of logical expressions and to test the correctness of logical expressions.

# Define a function to check if a number is odd
def is_odd(number):
  return number % 2 != 0

# Test the function with some numbers
print(is_odd(1))  # True
print(is_odd(2))  # False
print(is_odd(3))  # True

# Define a function to check if a number is within a certain range
def in_range(number, lower, upper):
  return lower <= number <= upper

# Test the function with some numbers
print(in_range(5, 1, 10))  # True
print(in_range(5, 6, 10))  # False
print(in_range(5, 1, 5))   # True

# Use a Boolean expression in an if statement
x = 5
if x > 0:
  print("x is positive.")

# Use a Boolean expression in a while loop
x = 5
while x > 0:
  print(x)
  x -= 1

# Use a truth table to test a logical expression
#
# Inputs:  A      B
# Output:  A and B
#
# A | B | A and B
# --+---+---------
# 0 | 0 |    0
# 0 | 1 |    0
# 1 | 0 |    0
# 1 | 1 |    1
True
False
True
True
False
True
x is positive.
5
4
3
2
1