class NumberOperations:
def __init__(self, number1, number2):
self.number1 = number1
self.number2 = number2
def add(self):
"""Returns the sum of the two numbers."""
return self.number1 + self.number2
def average(self):
"""Returns the average of the two numbers."""
return (self.number1 + self.number2) / 2
# Example usage:
if __name__ == "__main__":
# Create an instance of NumberOperations with two numbers
num_op = NumberOperations(10, 20)
# Calculate the sum and average of the numbers
sum_result = num_op.add()
average_result = num_op.average()
# Print the results
print(f"The sum of the numbers is: {sum_result}")
print(f"The average of the numbers is: {average_result}")
NumberOperations is the class that encapsulates the operations. It has two methods: add()
and average()
.
__init__
Initializes each instance of the class with two numbers, number1
and number2
.
add()
Calculates and returns the sum of the two numbers stored in the instance.
average()
Calculates and returns the average of the two numbers.
Under the if __name__ == "__main__"
block, the script creates an instance of NumberOperations, calls the methods to perform the calculations, and prints the results.
class GradeAccumulator:
# initialize the methods for the class
def __init__(self, scores):
self.scores = scores
# we will create methods to handle our requirements[total, max, min, gpa]
def totalScore(self):
score_total = sum(self.scores)
return score_total
# we will create a method to handle our max score
def maxScore(self):
score_max = max(self.scores)
return score_max
# we will create a method to handle our min scores
def minScore(self):
score_min = min(self.scores)
return score_min
def gpaFinder(self):
total_subjects = len(self.scores)
gpa_value = sum(self.scores) / total_subjects
return gpa_value
# we will create the objects for the class
student1_scores = [67, 65, 64, 63, 62, 61, 60, 78, 79, 77, 76, 75, 74, 73, 72]
student_lindsey = GradeAccumulator(student1_scores)
print("The total score of the student =", student_lindsey.totalScore())
The GradeAccumulator
class is designed to process a list of student scores and provide various statistical results about these scores.
__init__
This constructor method initializes an instance of the class with a list of scores. The scores are stored in the self.scores
attribute.
totalScore
This method calculates the total sum of the scores using the sum()
function and returns the result.
maxScore
Calculates and returns the maximum score from the list using the max()
function.
minScore
Calculates and returns the minimum score from the list using the min()
function.
gpaFinder
Calculates the average of the scores, which represents the Grade Point Average (GPA). This is done by dividing the total score by the number of subjects (length of the scores list).
An instance of the class is created with a specific student's scores. Methods are then called on this instance to print the total score of the student.
class GradeAccumulator:
# Initialize the methods for the class
def __init__(self, *scores):
self.scores = scores
# Method to calculate total scores for all students
def totalScore(self):
return [sum(scores) for scores in self.scores]
# Method to find the maximum score for each student
def maxScore(self):
return [max(scores) for scores in self.scores]
# Method to find the minimum score for each student
def minScore(self):
return [min(scores) for scores in self.scores]
# Method to calculate the average score for each student
def averageFinder(self):
averages = []
for scores in self.scores:
total_subjects = len(scores)
total_score = sum(scores)
averages.append(total_score / total_subjects)
return averages
# We will create the objects for the class
# We will create the objects for the class
student1_scores = [67, 65, 64, 63, 62, 61, 60, 78, 79, 77, 76, 75, 74, 73, 72]
student2_scores = [56, 65, 67, 63, 62, 61, 60]
student3_scores = [20, 22, 23, 24, 26, 78, 79, 88, 99]
students_record = GradeAccumulator(student1_scores, student2_scores, student3_scores)
print("The total score of the students =", students_record.totalScore())
print("The Maximum score of the students =", students_record.maxScore())
print("The Minimum score of the students =", students_record.minScore())
print("The average score of the students =", students_record.averageFinder())
print("Code Created by Pycent.com")
print("*"*35)
GradeAccumulator
This class is designed to manage score data for multiple students, allowing for the calculation of total, maximum, minimum, and average scores.
__init__(self, *scores)
The constructor takes a variable number of arguments, each representing the scores of a student as a list. These scores are stored in a tuple attribute self.scores
.
totalScore(self)
Calculates the total score for each student. It returns a list where each element is the sum of scores for a student.
maxScore(self)
Finds the maximum score for each student. Returns a list of maximum scores, one for each student.
minScore(self)
Finds the minimum score for each student. This method returns a list of the minimum scores, one for each student.
averageFinder(self)
Calculates the average score for each student. It computes this by dividing the total score by the number of subjects (scores) for each student and returns a list of these averages.
An instance of GradeAccumulator
is created with scores for three different students. Methods are then invoked to print the total, maximum, minimum, and average scores for these students.
Code Created by Pycent.com
***********************************
class Triangle:
def __init__(self, base, height):
"""
Initialize the properties of the Triangle.
:param base: The length of the base of the triangle.
:param height: The height of the triangle from its base.
"""
self.base = base
self.height = height
def area(self):
"""
Calculate and return the area of the triangle using the formula:
Area = (base * height) / 2
:return: The area of the triangle.
"""
return (self.base * self.height) / 2
# Example Area of triangle using OOPS-pycent.com:
triangle = Triangle(10, 5)
print("The area of the triangle is:", triangle.area()," SqUnits")
print("Code created and checked by Pycent.com")
print("*"*38)
Purpose: Defines a blueprint for creating a triangle object. Classes in OOP are templates for creating objects that encapsulate data and functionalities together.
Purpose: This method is called automatically when a new instance of the class (a new triangle) is created. It initializes the triangle's attributes.
Parameters:
Properties: self.base
and self.height
are instance variables that store the base and height of the triangle, making them available to other methods in the class.
Purpose: Calculates the area of the triangle based on its base and height.
Operation: Uses the formula for the area of a triangle \( \text{Area} = \frac{\text{base} \times \text{height}}{2} \).
Return Value: Returns the computed area, allowing it to be printed or used in further calculations.
Output:The area of the triangle is: 25.0 SqUnits
Code created and checked by Pycent.com
**************************************
A triangle object is created by passing the base and height to the Triangle class. This instance (triangle) is then used to call the area method, which calculates and prints the triangle's area.
Encapsulation: The triangle's data (its dimensions) and the methods that operate on the data (calculating the area) are encapsulated into a single manageable unit (the Triangle class).
Reusability: The Triangle class can be used to create multiple instances (multiple triangles), each with its own data, without the need for redundant code.
Scalability: Additional features like methods to calculate the perimeter or to scale the triangle can easily be added to the Triangle class, making the code more scalable and maintainable.
class Circle:
def __init__(self, radius):
"""
Initialize a Circle with its radius.
:param radius: The radius of the circle.
"""
self.radius = radius
def area(self):
"""
Calculate and return the area of the circle using the formula:
Area = π * radius^2
:return: The area of the circle.
"""
import math
return math.pi * self.radius ** 2
# Example usage created by pycent.com:
circle = Circle(5)
print("The area of the circle (without being rounded) is :", circle.area())
print("The area of the circle is(with being rounded) is :", round(circle.area()))
print("Code created and verified by Pycent.com")
Purpose: Defines a blueprint for creating a circle object. Classes in OOP are templates for creating objects that encapsulate data and functionalities together.
Purpose: This method is called automatically when a new instance of the class (a new circle) is created. It initializes the circle with a radius.
Parameter:
Purpose: Calculates the area of the circle based on its radius using the formula \( \text{Area} = \pi \times \text{radius}^2 \).
Operation: The method uses the value of π from Python's math module and squares the radius to compute the area.
Return Value: Returns the computed area, which can be printed or used in further calculations.
A circle object is created by passing the radius to the Circle class. This instance (circle) is then used to call the area method, which calculates and prints the circle's area.