Data Abstraction

Data Abstraction: Data abstraction is a fundamental concept in computer science and programming, often closely related to variables. Data abstraction involves simplifying complex systems by breaking them down into manageable parts and focusing on the essential characteristics while hiding the unnecessary details. Variables are an example of data abstraction because they allow us to assign a name or symbol to a value, essentially providing a meaningful label or description for that value.

Variables are essential in programming as they serve various purposes, especially when dealing with extensive lines of code. They provide a way to store and manage data, which can include various data types such as integers, booleans, lists, strings, and dictionaries. This abstraction simplifies the manipulation and utilization of data within a program, making it more organized and understandable. By associating values with variable names, programmers can work with data in a more intuitive and structured manner, leading to more efficient and maintainable code.

# Converting Sring to and from JSON

import json 
list = ["Vance", "Ronit", "Jared", "Ashwin"] 
json_obj = json.dumps(list) 
print(json_obj)
["Vance", "Ronit", "Jared", "Ashwin"]
# Classes and self

def __init__(self, name, age):
    self.name = name
    self.age = age

def myfunc(self):
    print("Hello my name is " + self.name)# Classes and self

def __init__(self, name, age):
    self.name = name
    self.age = age

def myfunc(self):
    print("Hello my name is " + self.name)

Algorithms

Algorithm: A finite set of instructions designed to achieve a particular task. Can be visualized as a sequence of steps that must be executed in a specific order. Iteration, or repetition, involves actions such as evaluating a condition, making decisions (yes or no), and performing certain steps if the condition is true. Algorithms can be represented through various means, including flowcharts that use arrows to denote decision points.

Basic mathematical operations include addition (a + b), subtraction (a - b), multiplication (a * b), division (a / b), and finding the modulus, which is the remainder when a is divided by b (a MOD b). In Python, the modulus operation is denoted by the ‘%’ symbol. When it comes to mathematical order of operations, remember that MOD is treated at the same level as multiplication and division in the PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction) hierarchy.

# Math 
num1 = 10
num2 = num1 / 2
num3 = 5 * num2 - 5
result = num2 % 3 * num1 + 4 - num3 / 2
print (result)
14.0
# Example Algorithim for Palindromes
def palindrome(input_str):
    # Remove spaces and convert the string to lowercase
    clean_str = input_str.replace(" ", "").lower()
    # Check if the cleaned string is equal to its reverse
    return clean_str == clean_str[::-1]


print(palindrome("racecar")) # True
print(palindrome("happy")) # False
True
False

Boolean If

Boolean: A data type that can take on one of two values: “true” or “false.” Boolean values are often used to represent the result of a comparison or a condition in computer programming.

If-Statements, AKA conditionals, are control structures in programming that execute a specific portion of code when a given expression or condition is satisfied. They are used to compare variables or evaluate conditions, and based on the result, they decide whether to run a particular block of code. The result of the evaluation is typically a Boolean value, which is either “true” or “false,” indicating whether the condition is met. If the condition is “true,” the code within the if-statement’s block is executed; otherwise, it is skipped.

# Example Boolean
boolean = True
print(boolean)  # Output: True

boolean = False
print(boolean)  # Output: False

boolean = 1
# boolean is no longer a boolean; it is now an integer
print(type(boolean))  # Output: <class 'int'>
True
False
<class 'int'>
# Prompt the user for their age
user_age = int(input("Please enter your age: "))

# Define a Boolean variable to check if the user is an adult
is_adult = user_age >= 18

# Check the condition and provide a response
if is_adult:
    print("You are an adult.")
else:
    print("You are not an adult yet.")
You are not an adult yet.

Iteration

Iteration is a critical concept in programming, involving the repetition of a set of instructions. It is a fundamental and powerful technique used for automating tasks, processing data, and implementing algorithms efficiently. There are two primary types of loops commonly used in programming:

For Loops: For loops are used to iterate over a sequence, which can be a list, tuple, string, range, or any other iterable object. They execute a block of code for each item in the sequence, providing a structured way to process elements one by one. For example, you can use a for loop to go through all the elements in a list and perform a specific action on each element.

While Loops: While loops are used to execute a block of code as long as a certain condition is true. They are particularly useful when you don’t know in advance how many times the code should be executed, and you rely on a condition to control the loop. Be careful with while loops to avoid potential infinite loops by ensuring that the condition eventually becomes false.

#simple for loop
numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)
1
2
3
4
5
# simple while loop
counter = 1

# Define the condition for the while loop
while counter <= 5:
    print(counter)
    counter += 1  # Increment the counter by 1 in each iteration
1
2
3
4
5
# Looping in lists
names = []

# Prompt the user to enter names and add them to the list
num_names = int(input("How many names would you like to enter? "))

for i in range(num_names):
    name = input(f"Enter name {i + 1}: ")
    names.append(name)

# Loop through the list of names and display them
print("List of names:")
for name in names:
    print(name)
List of names:
Vance
Ronit
Jared
Ashwin

Developing Algorithms

Algorithm: A set of clear, step-by-step instructions for solving a specific problem. It can be applied to similar problems and is used in various areas of life. Think of it like a routine that guides actions. In computer science, algorithms are crucial for automating tasks and allowing computers to solve problems independently, reducing the need for human intervention. They provide structure and efficiency in problem-solving across a wide range of applications.

# Simple tax algorithm
tax_rate = 0.05  # 5% tax rate

# Get the user's income as input
income = float(input("Enter your annual income: "))

# Calculate the tax amount
tax_amount = income * tax_rate

# Display the tax amount
print(f"Your tax amount is: ${tax_amount:.2f}")
Your tax amount is: $5000.00

Lists and Searches

Lists and Searches: A Python list is a versatile data structure that serves as an ordered and mutable collection of data objects. Unlike arrays in some other programming languages, Python lists can hold a mixture of data types, making them very flexible for storing and manipulating various kinds of information.

Note: Python uses a 0-based index for list elements, the first element is accessed with an index of 0, the second element with an index of 1, and so on.

How to Create a list:

If we want to create a list called “exampleList”: type exampleList = [].

Lists with elements would look like this: exampleList = [element1,element2,element3]

#Example List and appendin
shoppingList = []

while True:
    user_input = input("Enter an item for your shopping list (or 'q' to quit): ")  
    if user_input.lower() == 'q':
        break
    shoppingList.append(user_input)
print("Items You Want:", shoppingList)
Items You Want: ['cheese', 'ham', 'chips', 'milk']

Developing Procedures

Procedure: AKA methods or functions are different programming languages, named blocks of code that can accept parameters (input values) and return results. These procedures execute a set of statements on the provided parameters and yield a return value.

Parameters represent the input values that a procedure requires, and when the procedure is called, specific values, known as arguments, are passed as parameters.

Here’s a pseudo-code example of a long procedure involving applying a discount and then a tax to an item’s cost:

PROCEDURE applyDiscount(cost, percentDiscounted) {
    temp  100 - percentDiscounted
    temp  temp / 100
    cost  cost * temp
    RETURN(cost)
}

price  applyDiscount(60, 20)

Libraries

Library: A file that holds useful procedures for a program. An API, or Application Program Interface, provides guidelines for how these procedures work and are used. It enables these imported procedures to communicate with the rest of your code.

Note: Modern companies and programmers often rely on various libraries like Requests, Pillow, Pandas, NumPy, SciKit-Learn, TensorFlow, and Matplotlib to create libraries.

#importing and using a library
from PIL import Image

# Example usage:
image = Image.open('/home/vancer/vscode/cspblog2/images/batgif.gif')#This is the path of the image
image.show()

png