0% found this document useful (0 votes)
19 views12 pages

Dani Zaeem 480307 Python First Assignment

Uploaded by

Danny Zaeem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views12 pages

Dani Zaeem 480307 Python First Assignment

Uploaded by

Danny Zaeem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Dani_Zaeem_First_Assignment_480307

November 26, 2024

[7]: from datetime import datetime, timedelta

# Author
class Author:
def __init__(self, name, nationality):
self.name = name
self.nationality = nationality

def __str__(self):
return f"{self.name} ({self.nationality})"

# Book
class Book:
def __init__(self, title, author, publication_date):
self.title = title
self.author = author # Author example
self.publication_date = publication_date
self.is_loaned = False # the book is loaned out or not

def __str__(self):
return f"'{self.title}' by {self.author.name} (Published: {self.
↪publication_date})"

# Patron
class Patron:
def __init__(self, name):
self.name = name
self.borrowing_history = [] # borrowed books and dates

def borrow_book(self, book, days=50):


if not book.is_loaned:
loan_date = datetime.now()
due_date = loan_date + timedelta(days=days)
book.is_loaned = True
self.borrowing_history.append((book, loan_date, due_date))

1
print(f"{self.name} borrowed '{book.title}' until {due_date.
↪strftime('%Y-%m-%d')}.")
else:
print(f"Sorry, '{book.title}' is already loaned out.")

def return_book(self, book):


for record in self.borrowing_history:
if record[0] == book and book.is_loaned:
book.is_loaned = False
print(f"{self.name} returned '{book.title}'.")
return
print(f"{self.name} has not borrowed '{book.title}'.")

def __str__(self):
return f"Patron: {self.name}, Borrowing History: {[book.title for book,␣
↪_, _ in self.borrowing_history]}"

# Class for Library


class Library:
def __init__(self):
self.books = []
self.authors = []
self.patrons = []

def add_author(self, name, nationality):


author = Author(name, nationality)
self.authors.append(author)
print(f"Author '{name}' added.")
return author

def add_book(self, title, author, publication_date):


book = Book(title, author, publication_date)
self.books.append(book)
print(f"Book '{title}' added.")
return book

def add_patron(self, name):


patron = Patron(name)
self.patrons.append(patron)
print(f"Patron '{name}' added.")
return patron

def query_books(self):
for book in self.books:
status = "Available" if not book.is_loaned else "Loaned Out"
print(f"{book} - Status: {status}")

2
def query_authors(self):
for author in self.authors:
print(author)

def query_patrons(self):
for patron in self.patrons:
print(patron)

# Example
if __name__ == "__main__":

library = Library()

# Add Authors
author1 = library.add_author("Naguib Mahfouz", "Egyptian")
author2 = library.add_author("Mahmoud Darwish", "Jordanian")

# Add Books
book1 = library.add_book("Palace Walk", author1, "1956")
book2 = library.add_book("Memory for Forgetfulness", author2, "1987")

# Add Patrons
patron1 = library.add_patron("Ahmed")
patron2 = library.add_patron("Layla")

# Borrow and Return Books


patron1.borrow_book(book1)
patron2.borrow_book(book2)
patron1.return_book(book1)

# Query Library
print("\nLibrary Books:")
library.query_books()

print("\nLibrary Authors:")
library.query_authors()

print("\nLibrary Patrons:")
library.query_patrons()

Author 'Naguib Mahfouz' added.


Author 'Mahmoud Darwish' added.
Book 'Palace Walk' added.
Book 'Memory for Forgetfulness' added.
Patron 'Ahmed' added.
Patron 'Layla' added.

3
Ahmed borrowed 'Palace Walk' until 2025-01-15.
Layla borrowed 'Memory for Forgetfulness' until 2025-01-15.
Ahmed returned 'Palace Walk'.

Library Books:
'Palace Walk' by Naguib Mahfouz (Published: 1956) - Status: Available
'Memory for Forgetfulness' by Mahmoud Darwish (Published: 1987) - Status: Loaned
Out

Library Authors:
Naguib Mahfouz (Egyptian)
Mahmoud Darwish (Jordanian)

Library Patrons:
Patron: Ahmed, Borrowing History: ['Palace Walk']
Patron: Layla, Borrowing History: ['Memory for Forgetfulness']

[ ]:

4
Dani_Zaeem_First_Assignment_480307_

November 26, 2024

[13]: from datetime import datetime

# Cars
class Car:
def __init__(self, manufacturer, model, rental_cost):
self.manufacturer = manufacturer
self.model = model
self.rental_cost = rental_cost
self.rental_income = 0 # income generated by this car
self.is_rented = False # the car is currently rented or not

def __str__(self):
return f"{self.manufacturer} {self.model} (Cost per day: ${self.
↪rental_cost})"

# Customers
class Customer:
def __init__(self, name, contact_info, credit_card):
self.name = name
self.contact_info = contact_info
self.credit_card = credit_card
self.rental_history = [] # Tracks past rentals

def __str__(self):
return f"Customer: {self.name}, Contact: {self.contact_info}"

# Rental Records
class RentalRecord:
def __init__(self, customer, car, rental_date, rental_days, rental_cost):
self.customer = customer
self.car = car
self.rental_date = rental_date
self.rental_days = rental_days
self.rental_cost = rental_cost

def __str__(self):

1
return (f"Rental Record: {self.customer.name} rented {self.car.
↪manufacturer} {self.car.model} "
f"on {self.rental_date.strftime('%Y-%m-%d')} for {self.
↪rental_days} days "

f"at a cost of ${self.rental_cost}.")

# the Rental System


class CarRentalSystem:
def __init__(self):
self.cars = []
self.customers = []
self.rental_records = []

def add_car(self, manufacturer, model, rental_cost):


car = Car(manufacturer, model, rental_cost)
self.cars.append(car)
print(f"Car added: {manufacturer} {model} (${rental_cost}/day)")

def add_customer(self, name, contact_info, credit_card):


customer = Customer(name, contact_info, credit_card)
self.customers.append(customer)
print(f"Customer added: {name}")

def rent_car(self, customer_name, car_model, rental_days):


# the customer and the car
customer = next((c for c in self.customers if c.name == customer_name),␣
↪None)

car = next((c for c in self.cars if c.model == car_model and not c.


↪is_rented), None)

if not customer:
print(f"Customer '{customer_name}' not found.")
return
if not car:
print(f"Car '{car_model}' is either not available or already rented.
↪")
return

# rental cost and rental record


rental_cost = car.rental_cost * rental_days
rental_date = datetime.now()
record = RentalRecord(customer, car, rental_date, rental_days,␣
↪rental_cost)

# car status and customer rental history


car.is_rented = True

2
car.rental_income += rental_cost
customer.rental_history.append(record)
self.rental_records.append(record)

print(f"{customer.name} rented {car.manufacturer} {car.model} for␣


↪{rental_days} days at ${rental_cost}.")

def return_car(self, car_model):


# Find the car and mark it as returned
car = next((c for c in self.cars if c.model == car_model and c.
↪is_rented), None)

if car:
car.is_rented = False
print(f"Car '{car.model}' has been returned.")
else:
print(f"Car '{car_model}' is not currently rented.")

def calculate_income(self):
# Calculate and display total income for all cars
total_income = sum(car.rental_income for car in self.cars)
print(f"Total income for all cars: ${total_income}")

# income
for car in self.cars:
print(f"Total income for {car.manufacturer} {car.model}: ${car.
↪rental_income}")

def view_rental_history(self, customer_name):


customer = next((c for c in self.customers if c.name == customer_name),␣
↪None)

if not customer:
print(f"Customer '{customer_name}' not found.")
return
print(f"Rental history for {customer.name}:")
for record in customer.rental_history:
print(record)

# Example
if __name__ == "__main__":
# Initialize the system
rental_system = CarRentalSystem()

# Add Cars
rental_system.add_car("Mercedes", "S500", 150)
rental_system.add_car("Nissan", "Sunny", 40)

# Add Customers

3
rental_system.add_customer("Dani", "[email protected]", "5342-4356-7536-3467")
rental_system.add_customer("Florian", "[email protected]",␣
↪"6456-3673-5673-4578")

# Rent and Return Cars


rental_system.rent_car("Dani", "S500", 5)
rental_system.rent_car("Florian", "Sunny", 7)
rental_system.return_car("S500")

# View Rental History and Income


rental_system.view_rental_history("Dani")
rental_system.view_rental_history("Florian")
rental_system.calculate_income()

Car added: Mercedes S500 ($150/day)


Car added: Nissan Sunny ($40/day)
Customer added: Dani
Customer added: Florian
Dani rented Mercedes S500 for 5 days at $750.
Florian rented Nissan Sunny for 7 days at $280.
Car 'S500' has been returned.
Rental history for Dani:
Rental Record: Dani rented Mercedes S500 on 2024-11-26 for 5 days at a cost of
$750.
Rental history for Florian:
Rental Record: Florian rented Nissan Sunny on 2024-11-26 for 7 days at a cost of
$280.
Total income for all cars: $1030
Total income for Mercedes S500: $750
Total income for Nissan Sunny: $280

[ ]:

4
Untitled7

November 26, 2024

[1]: class Student:


def __init__(self, name, age, student_id):
self.name = name
self.age = age
self.student_id = student_id
self.courses = {} # Dictionary to store courses and grades

def enroll_course(self, course, grade=None):


self.courses[course.name] = {"course": course, "grade": grade}

def calculate_average_grade(self):
grades = [info["grade"] for info in self.courses.values() if␣
↪info["grade"] is not None]

return sum(grades) / len(grades) if grades else 0

def calculate_total_credit_hours(self):
return sum(info["course"].credit_hours for info in self.courses.
↪values())

class Course:
def __init__(self, name, credit_hours):
self.name = name
self.credit_hours = credit_hours

class GradeSystem:
def __init__(self):
self.students = []
self.courses = []

def add_student(self, name, age, student_id):


student = Student(name, age, student_id)
self.students.append(student)
print(f"Student {name} added.")

def add_course(self, name, credit_hours):

1
course = Course(name, credit_hours)
self.courses.append(course)
print(f"Course {name} added.")

def enroll_student_in_course(self, student_id, course_name, grade=None):


student = self._find_student(student_id)
course = self._find_course(course_name)
if student and course:
student.enroll_course(course, grade)
print(f"Student {student.name} enrolled in course {course.name}.")
else:
print("Student or course not found.")

def query_student_grades(self, student_id):


student = self._find_student(student_id)
if student:
print(f"Grades for {student.name}:")
for course_name, info in student.courses.items():
grade = info["grade"]
print(f" Course: {course_name}, Grade: {grade}")
else:
print("Student not found.")

def query_course_info(self, course_name):


course = self._find_course(course_name)
if course:
print(f"Course: {course.name}, Credit Hours: {course.credit_hours}")
else:
print("Course not found.")

def _find_student(self, student_id):


return next((student for student in self.students if student.student_id␣
↪== student_id), None)

def _find_course(self, course_name):


return next((course for course in self.courses if course.name ==␣
↪course_name), None)

# Example usage
if __name__ == "__main__":
system = GradeSystem()

# Add students
system.add_student("Dani", 20, "S001")
system.add_student("Müller", 22, "S002")

2
# Add courses with updated credit hours
system.add_course("Music", 6)
system.add_course("Programming", 12)
system.add_course("Physics", 9)

# Enroll students in courses and record grades


system.enroll_student_in_course("S001", "Music", 95)
system.enroll_student_in_course("S001", "Programming", 88)
system.enroll_student_in_course("S002", "Physics", 80)
system.enroll_student_in_course("S002", "Music", 85)

# Query student grades


system.query_student_grades("S001")
system.query_student_grades("S002")

# Query course information


system.query_course_info("Music")

# Calculate and display grades and total credit hours for each student
dani = system._find_student("S001")
print(f"{dani.name}'s Average Grade: {dani.calculate_average_grade()}")
print(f"{dani.name}'s Total Credit Hours: {dani.
↪calculate_total_credit_hours()}")

mueller = system._find_student("S002")
print(f"{mueller.name}'s Average Grade: {mueller.
↪calculate_average_grade()}")

print(f"{mueller.name}'s Total Credit Hours: {mueller.


↪calculate_total_credit_hours()}")

Student Dani added.


Student Müller added.
Course Music added.
Course Programming added.
Course Physics added.
Student Dani enrolled in course Music.
Student Dani enrolled in course Programming.
Student Müller enrolled in course Physics.
Student Müller enrolled in course Music.
Grades for Dani:
Course: Music, Grade: 95
Course: Programming, Grade: 88
Grades for Müller:
Course: Physics, Grade: 80
Course: Music, Grade: 85
Course: Music, Credit Hours: 6
Dani's Average Grade: 91.5

3
Dani's Total Credit Hours: 18
Müller's Average Grade: 82.5
Müller's Total Credit Hours: 15

[ ]:

You might also like