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_LEFT()
ROTATE_LEFT()
ROTATE_LEFT()
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_LEFT()
ROTATE_LEFT()
ROTATE_LEFT()
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