OOP exercices notebook 1
Probelm 1¶
Create a class Rectangle that represents a rectangle. The class should have properties width and height, and a method area that returns the area of the rectangle.
## Class implementation
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
## Object declaration
rect1 = Rectangle(3, 4)
rect2 = Rectangle(5, 6)
print(rect1.area())
# Output: 12
print(rect2.area())
# Output: 30
12 30
Probelm 2¶
Create a class Circle with a property radius and a method area that returns the area of the circle.
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
circle = Circle(5)
print(circle.area())
# Output: 78.53981633974483
78.53981633974483
Probelm 3¶
Create a class Account that represents a bank account. The class should have a method deposit that allows you to deposit money into the account, and a method withdraw that allows you to withdraw money from the account. The class should also have a property balance that represents the current balance of the account.
## Class implementation
class Account:
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
def deposit(self, amount):
self.balance += amount
return str(amount)+ "has been deposited"
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
return str(amount) +"has been withdrawn"
else:
return "Insufficient funds"
## Object declaration
account = Account("John", 1000)
print(account.deposit(500))
print(account.withdraw(1500))
print(account.withdraw(500))
500has been deposited 1500has been withdrawn Insufficient funds
Probelm 4¶
Create a class Book with properties title, author, and pages and a method info that returns a string with information about the book.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def info(self):
return f"{self.title} by {self.author}, {self.pages} pages"
book = Book("To Kill a Mockingbird", "Harper Lee", 281)
print(book.info())
# Output: To Kill a Mockingbird by Harper Lee, 281 pages
To Kill a Mockingbird by Harper Lee, 281 pages
Probelm 5¶
Create a class Movie with properties title, director, and year and a method play that prints "Playing the movie [title]...".
class Movie:
def __init__(self, title, director, year):
self.title = title
self.director = director
self.year = year
def play(self):
print(f"Playing the movie {self.title}...")
movie = Movie("The Shawshank Redemption", "Frank Darabont", 1994)
movie.play()
# Output: Playing the movie The Shawshank Redemption...
Playing the movie The Shawshank Redemption...