Data Abstraction

Variables are considered abstraction as they assign a value to another value. In other words, they basically describe values to each other. Variables are important as it can be used in many different uses such as they can store useful information, especially if you have a long lines of code. Variables are mostly used to store data such as numbers (we are going to go over integers today), booleans, lists, strings and dictionaries.

Data Types:

Integer: A whole number Boolean: True or False based on operators String: Anything that contains “{text is stored in here}”

# Converting Sring to and from JSON

import json 
list = ["Bill", "Bob", "Ben", "Bailey"] 
json_obj = json.dumps(list) 
print(json_obj)
["Bill", "Bob", "Ben", "Bailey"]
# 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 that accomplish a specific task. Algorithm is like a list of steps that occur in a specific/particular order. Iteration/repetition→ First step, second step, continue condition, Yes or no, step to do if true Ways to write algorithm: flow chart(use arrows to tell decision) Addition: a + b Subtraction: a - b Multiplication: a * b Division: a / b Modulus (remainder of a/b): a MOD b For python it is % Math in order of operations MOD is held to the value of multiplication + division in PEMDAS

# Math 
num1 = 40
num2 = num1 / 2
num3 = 5 * num2 + 3
result = num2 % 3 * num1 + 4 - num3 / 2
print (result)
32.5
# 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("taco cat")) # True
print(palindrome("hi")) # False
True
False

Boolean If

Boolean: Data-type that can either be true or false If-Statements/Conditionals: Self, explanatory, runs a portion of code if expression/condition is satisfied. Used to compare two variables, returns a boolean

Relational Operators

== Checks if two variables are equal != Checks if two variables are not equal a > b Checks if variable a is greater than b a < b Checks if variable a is less than b a >= b and a <= b Same as above, but greater than or equal to and less than or equal to

# Example Boolean
boolean = True
print(boolean)
boolean = False
print(boolean)
boolean = 1
## boolean is not longer a boolean, now an integer
print(type(boolean))
True
False
<class 'int'>
#Example If
number = int(input('Enter a number: '))

if (number % 2 == 0):
    print('Number is even')
else: 
    print('Number is odd')
Number is odd

Iteration

Loops are essential for repetitive tasks and are a fundamental concept in programming. We will cover different types of loops, advanced loop techniques, and how to work with lists and dictionaries using loops.

For Loops

Used to iterate over a sequence (such as a list, tuple, string, or range) Executes a block of code for each item in the sequence

While Loops

Used to execute a block of code as long as a condition is true

#For Loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
apple
banana
cherry
# Looping in lists 
numbers = [1, 2, 3, 4]
for num in numbers:
    print(num)
    
person = {"name": "Ronit", "age": 15, "city": "San Diego"}
for key, value in person.items():
    print(key, ":", value)

1
2
3
4
name : Ronit
age : 15
city : San Diego

Developing Algorithms

An algorithm is a procedure or formula used for solving a problem. It has a sequence of events, inputs, and outputs.

Algorithms are used in many different aspect of life. For example a form of routine is an algorithm as it is a series of specified events.

It solves a problem in a way that it can be applied to any similar problem. It allows the computer to solve the problem on its own w/o any form of human interference.

# Example Tax Algorithm 
print("What is the cost of the item?")
cost = int(input())
tag = bool(input())

if tag == True: # Check if it is green tag (refer to lines above)
    cost = 0.75 * cost
if tag == False: # Check if it is green tag (refer to lines above)
    cost = 0.40 * cost
cost = 1.10 * cost # accounting for tax
What is the cost of the item?

Lists and Searches

A Python list is an ordered and changeable collection of data objects. Unlike an array, which can contain objects of a single type, a list can contain a mixture of objects. They start from 0. (The 1st element would actually be the 0th element)

How to Create a list

In order to create a list named “aList”, type aList = []. This creates an empty list. A list with elements would look like this aList = [element1,element2,element3]

#Example List plus appending
aList = []

while True:
    user_input = input("Enter an item you want (or 'q' to quit): ")  
    if user_input.lower() == 'q':
        break
    aList.append(user_input)
print("Things You Want:", aList)
Things You Want: ['fornite', 'cats']

Developing Procedures

A procedure is a named group of code that has paramaters and return values. Procedures are known as methods or functions depending on the language.

A procedure executes the statements within it on the parameters to provide a return value.

Paramaters are input values of a procedure that are specified by arguments.Arguments specify the values of the parameters when a procedure is called.

#Psuedo Cod for long Prodcedure involving tax

A 60$ item recieves a 20% discount and taxed at 8%. PROCEDURE applyDiscount(cost, percentDiscounted) { temp ← 100 - percentDiscounted temp← temp/ 100 cost ← cost *temp RETURN(cost) }

price ← applyDiscount(60, 20) This is how we get the final price with the discount by calling the procedure and assigning it to the price variable.

PROCEDURE applyTax(cost, percentTaxed) { temp ← 100 + percentTaxed temp← temp/ 100 cost ← cost *temp RETURN(cost) } price ← applyTax(price, 8) This applys the 8% tax to the price determined after the discount.

Libraries

A file that contains procedures that can be used in a program is called a library. An Application Program Interface, or API, contains specifications for how the procedures in a library behave and can be used. It allows the imported procedures from the library to interact with the rest of your code.

There are many types of libraries that modern day companies use, such as Requests, Pillow, Pandas, NumPy, SciKit-Learn, TensorFlow, and Matplotlib. Requests: The Requests library simplifies making HTTP requests in Python, making it easy to interact with web services and retrieve data from websites.

#importing and using a library
from PIL import Image

# Example usage:
image = Image.open('/home/lincolnc2008/vscode/student3/images/frog-game.jpg')#This is the path of the image
image.show()
# using numpy array on a list 

import numpy as np

# Example usage:
arr = np.array([1, 2, 3, 4, 5])
print(arr)
[1 2 3 4 5]