3.14 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.

Types of Libraries

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.

Pillow: Pillow is a powerful image processing library for opening, manipulating, and saving various image formats in Python.

Pandas: Pandas is a data manipulation and analysis library for efficiently working with structured data, including data import, cleaning, transformation, and analysis in tabular form.

NumPy: NumPy is a fundamental library for numerical computing in Python, providing support for multidimensional arrays and a wide range of mathematical functions.

Scikit-Learn: Scikit-Learn is a machine learning library that offers simple and efficient tools for data analysis and modeling, including classification, regression, and clustering.

TensorFlow: TensorFlow is an open-source machine learning framework that facilitates deep learning and neural network development, supporting tasks like image recognition and natural language processing.

Matplotlib: Matplotlib is a versatile plotting library for creating 2D and 3D visualizations and figures in Python, enabling a wide range of plots, charts, and graphs for data visualization and analysis.

Libraries are, at their heart, a collection of other people’s code, and it would be difficult to understand how the procedures should be used without documentation. APIs explain how two separate pieces of software interact with each other, and they also need documentation to keep this communication going.

Intro to Popcorn Hack 1

We have now hopefully all done or seen this type of question about getting a robot from point a to point b. But this can be very tedious because it may take a lot of code to do that. Luckily, there’s a saving grace called procedures, procedures essentially shorten the amount of code that is needed. So for a robot example we have displayed, we will use the procedure “moveBackwards” to shorten the amount of code we would normally need. This will rotate our triangle 180 degrees. Here is the example and solution

#Pseudo Code
CAN_MOVE_BACKWARD()
MOVE_FORWARD()
MOVE_FORWARD()
ROTATE_RIGHT()
MOVE_FORWARD()
MOVE_FORWARD()

# Python Code
def CAN_MOVE_BACKWARD():
    # Implement the logic to check if you can move backward
    return True  # Replace with your logic

def MOVE_FORWARD():
    # Implement the logic to move forward
    print("Moving forward")

def ROTATE_LEFT():
    # Implement the logic to rotate to the left
    print("Rotating left")

# Perform the movements
if CAN_MOVE_BACKWARD():
    MOVE_FORWARD()
    MOVE_FORWARD()
    ROTATE_RIGHT()
    MOVE_FORWARD()
    MOVE_FORWARD()

Popcorn Hack #1

Here you have another problem, use these following commands to solve the problem.

# Code goes here

Documentation

Documentation is what you need to know about the procedure. For example, Documentation for the calcAverage function is shown below and with this information, you can use this procedure without knowing what is really going on. The purpose of this is that it makes your coding go a lot faster, which most tech companies find very useful in today’s society.

Popcorn Hack #2

Use calcAverage procedure to get average for a set of grades (gpa)

#Pseudo Code
FUNCTION calc_quotient(grade, credit):
    RETURN grade * credit

FUNCTION calculate_gpa():
    PROMPT user to enter the number of courses
    SET total_credits to 0
    SET total_quotient to 0

    FOR each course in range(num_courses):
        PROMPT user to enter the grade for the course (0-4.0 scale)
        PROMPT user to enter the credit hours for the course
        SET course_grade to user input grade
        SET course_credit to user input credit

        SET course_quotient to calc_quotient(course_grade, course_credit)

        ADD course_quotient to total_quotient
        ADD course_credit to total_credits

    IF total_credits is not equal to 0 THEN
        SET gpa to total_quotient divided by total_credits
        PRINT "Your GPA is: ", gpa formatted to two decimal places
    ELSE
        PRINT "Total credits cannot be zero. Please enter valid credit hours."

CALL calculate_gpa()

CACLGPA PSEUDOCODE


FUNCTION calculateGPA(grades)
    totalCreditPoints = 0
    totalCredits = 0

    FOR EACH grade IN grades
        credit = grade.credit
        score = grade.score
        creditPoints = calcquotient(credit, score)
        totalCreditPoints = totalCreditPoints + creditPoints
        totalCredits = totalCredits + credit
    END FOR

    IF totalCredits > 0
        GPA = totalCreditPoints / totalCredits
    ELSE
        GPA = 0  // To handle division by zero
    END IF

    RETURN GPA
END FUNCTION

FUNCTION calcquotient(credit, score)
    // Calculate credit points based on a scale (e.g., 4.0 for A, 3.0 for B, etc.)
    // You can define the scale based on your institution's grading system.
    // For example, if you use a 4.0 scale:
    IF score == "A"
        creditPoints = 4.0 * credit
    ELSE IF score == "B"
        creditPoints = 3.0 * credit
    ELSE IF score == "C"
        creditPoints = 2.0 * credit
    ELSE IF score == "D"
        creditPoints = 1.0 * credit
    ELSE
        creditPoints = 0.0  // Handle unknown or failing grades
    END IF

    RETURN creditPoints
END FUNCTION

# Python Code 
# Define the function calc_quotient
def calc_quotient(grade, credit):
    return grade * credit

# Define the function calculate_gpa
def calculate_gpa():
    num_courses = int(input("Enter the number of courses: "))
    total_credits = 0
    total_quotient = 0

    for _ in range(num_courses):
        course_grade = float(input("Enter the grade for the course (0-4.0 scale): "))
        course_credit = float(input("Enter the credit hours for the course: "))

        course_quotient = calc_quotient(course_grade, course_credit)

        total_quotient += course_quotient
        total_credits += course_credit

    if total_credits != 0:
        gpa = total_quotient / total_credits
        print(f"Your GPA is: {gpa:.2f}")
    else:
        print("Total credits cannot be zero. Please enter valid credit hours.")

# Call the calculate_gpa function
calculate_gpa()

# Code goes here

API's

A file that contains these procedures is a library. API’s provide specifications for how procedures in a library behave and can be used. In other words, API is a documentation for these libraries. Many large tech companies provide API for programmers to interact with their product.

Example of Libraries

A good example of a library is the collegeboard AP CSP exam reference sheet. This is only 1 of the 6 pages. This includes a lot of key information that students will have access to during the AP exam.

Popcorn Hack 3

Here is 1 of the 3 procedures from the exam reference sheet The popcorn hack is that you have to find the largest number (findLargestNumber) using this procedure

# Pseudo Code
PROCEDURE procName(parameter1, parameter2, ...)
{
    // Block of statements to perform some computation
    // using the parameters.
    
    // Calculate the result or expression.
    result <- some_expression
    
    // Return the result.
    RETURN result
}
# Python Code
# Define a Python function with parameters
def procName(parameter1, parameter2, ...):
    # Block of statements to perform some computation
    # using the parameters.
    
    # Calculate the result or expression.
    result = some_expression
    
    # Return the result.
    return result

# Code goes here

Optional Popcorn Hacks For Extra Credit!

These hacks are completely optional and are for extra credit! For the first one, find the average of all numbers For the second one, find the factorial of a number

# Code for #1 goes here
# Code for #2 goes here

Homework!

For our homework hack, you are given 4 procedures right here, choose the right one (there is only 1 right answer) and write code for a gpa calculation.

# Code goes here

Thank You!

import requests

# Define the URL you want to make a GET request to
url = 'https://jsonplaceholder.typicode.com/posts/1'  # This is an example JSON API

# Make the GET request
response = requests.get(url)

# Check the status code of the response
if response.status_code == 200:
    print(f"Success! The status code is {response.status_code}.")
    # Print the JSON content of the response
    print("Response content:")
    print(response.json())
else:
    print(f"Request failed with status code {response.status_code}.")
Success! The status code is 200.
Response content:
{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'}
import numpy as np

# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])

# Basic array operations
print("Array:", arr)
print("Shape:", arr.shape)
print("Size:", arr.size)
print("Data type:", arr.dtype)
print("Sum:", arr.sum())
print("Mean:", arr.mean())
print("Max:", arr.max())
print("Min:", arr.min())

# Reshaping the array
reshaped_arr = arr.reshape(1, 5)
print("Reshaped array:", reshaped_arr)

# Element-wise operations
arr_squared = arr ** 2
print("Squared array:", arr_squared)

# Slicing and indexing
sliced_arr = arr[1:4]
print("Sliced array:", sliced_arr)

# Element-wise multiplication
arr2 = np.array([2, 2, 2, 2, 2])
product = arr * arr2
print("Element-wise product:", product)

# Matrix operations
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
matrix_product = np.dot(matrix_a, matrix_b)
print("Matrix product:")
print(matrix_product)
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

Cell In[4], line 1
----> 1 import numpy as np
      3 # Create a NumPy array
      4 arr = np.array([1, 2, 3, 4, 5])


ModuleNotFoundError: No module named 'numpy'
import pandas as pd

# Define the path to the CSV file
csv_file = 'data.csv'

# Read the CSV data into a Pandas DataFrame
df = pd.read_csv(csv_file)

# Display the first few rows of the DataFrame
print("First few rows of the data:")
print(df.head())

# Calculate the mean age
mean_age = df['Age'].mean()
print(f"Mean age: {mean_age:.2f}")

# Calculate the number of people in each location
location_counts = df['Location'].value_counts()
print("Number of people in each location:")
print(location_counts)

---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

Cell In[5], line 1
----> 1 import pandas as pd
      3 # Define the path to the CSV file
      4 csv_file = 'data.csv'


ModuleNotFoundError: No module named 'pandas'
import matplotlib.pyplot as plt

# Sample data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [15, 30, 45, 20]

# Create a bar chart
plt.bar(categories, values)

# Add labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart Example')

# Show the chart
plt.show()

---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

Cell In[6], line 1
----> 1 import matplotlib.pyplot as plt
      3 # Sample data
      4 categories = ['Category A', 'Category B', 'Category C', 'Category D']


ModuleNotFoundError: No module named 'matplotlib'
from PIL import Image
# Example usage:
image = Image.open('/Users/sergis/vscode/sergiStudent/images/frog1.png')#This is the path of the image
image.show()
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

Cell In[8], line 1
----> 1 from PIL import Image
      2 # Example usage:
      3 image = Image.open('/Users/sergis/vscode/sergiStudent/images/frog1.png')#This is the path of the image


ModuleNotFoundError: No module named 'PIL'