Social Icons

Friday, February 28, 2020

Exercises with solutions on OOP - object oriented programming in Python

Exercise 41. Rectangle class: ||  Solution

  1. Write a Rectangle class in Python language, allowing you to build a rectangle with length and width attributes.
  2. Create a Perimeter() method to calculate the perimeter of the rectangle and a Area() method to calculate the area of ​​the rectangle.
  3. Create a method display() that display the length, width, perimeter and area of an object created using an instantiation on rectangle class.
  4. Create a Parallelepipede child class inheriting from the Rectangle class and with a height attribute and another Volume() method to calculate the volume of the Parallelepiped.

Exercice 42: Person class and child Student class ||  Solution

  1. Create a Python class Person with attributes: name and age of type string.
  2. Create a display() method that displays the name and age of an object created via the Person class.
  3. Create a child class Student  which inherits from the Person class and which also has a section attribute.
  4. Create a method displayStudent() that displays the name, age and section of an object created via the Student class.
  5. Create a student object via an instantiation on the Student class and then test the displayStudent method.

Exercise 43. Bank Account class: ||  Solution

  1. Create a Python class called BankAccount which represents a bank account, having as attributes: accountNumber (numeric type), name (name of the account owner as string type), balance.
  2. Create a constructor with parameters: accountNumber, name, balance.
  3. Create a Deposit() method which manages the deposit actions.
  4. Create a Withdrawal() method  which manages withdrawals actions.
  5. Create an bankFees() method to apply the bank fees with a percentage of 5% of the balance account.
  6. Create a display() method to display account details.
  7. Give the complete code for the  BankAccount class.

Exercise 44. Circle class || Solution

1 - Define a Circle class allowing to create a circleC (O, r) with center O(a, b) and radius r using the constructor:
    def __init__(self,a,b,r):         
        self.a = a         
        self.b = b         
        self.r = r
2 - Define a Area() method of the class which calculates the area of ​​the circle.
3 - Define a Perimeter() method of the class which allows you to calculate the perimeter of the circle.
4 - Define a testBelongs() method of the class which allows to test whether a point A(x, y) belongs to the circle C(O, r) or not.

Exercise 45. Computation class || Solution

1 - Create a Coputation class with a default constructor (without parameters) allowing to perform various calculations on integers numbers.
2 - Create a method called Factorial() which allows to calculate the factorial of an integer. Test the method by instantiating the class.
3 - Create a method called Sum() allowing to calculate the sum of the first n integers 1 + 2 + 3 + .. + n. Test this method.
4 - Create a method called testPrim() in  the Calculation class to test the primality of a given integer. Test this method.
4 - Create  a method called testPrims() allowing to test if two numbers are prime between them.
5 - Create a tableMult() method which creates and displays the multiplication table of a given integer. Then create an allTablesMult() method to display all the integer multiplication tables 1, 2, 3, ..., 9.
6 - Create a static listDiv() method that gets all the divisors of a given integer on new list called  Ldiv. Create another listDivPrim() method that gets all the prime divisors of a given integer.

Exercise 46 Class Book || Solution

  1.  Define a Book class with the following attributes: Title, Author (Full name), Price.
  2. Define a constructor used to initialize the attributes of the method with values entered by the user.
  3. Set the View() method to display information for the current book.
  4. Write a program to testing the Book class.

Exercise 47 Class Geometry || Solution

Write a Geometry class with default constructor having no parameters.
  1. Write a methode in Geometry class called distance() that allow to compute a distance between two points A = (a1, a2), B = (b1, b2) (with the convention: a point M is identified with its pair of coordinates M = ( x, y)).
  2.  Write a methode in Geometry class called middle() allowing to determine the midle of bipoint (A,B).
  3. Write method called trianglePerimeter() allowing to compute the perimeter of triangle
  4. Write method called triangleIsoscel() which returns a True if the triangle is isoscel and False if not.

Exercise 48 Class String || Solution

Coding a class named myString inheriting from the str class allowing to endow strings with append() and pop () methods doing the same operations as those of lists class.

Exercise 49 Class Tkinter Extended|| Solution

1- Create a class called TK_extended which inherits from TK class and having the attributes:
- Master: that represents the name of the main window
- title: that represents the title of the main window
2 - Create a method called create() that creates the window
3 - Create a method called resize(width, height) that can resize the window.
4 - Create a method called generate() to generate the window

Younes Derfoufi


  1. Replies
    1. This is what I come up with a code by myself. Please let me know if you got your opinion. I would like to hear what others think of my code> Thank you!


      import math

      class Computation:
      #default constructor
      def __init__(self):

      #factorial of a number
      def factorial(self, integer):
      if integer == 0:
      return 1
      return integer * self.factorial(integer - 1)

      #sum of first n number
      def Sum(self, integer):
      return sum(range(1, integer + 1))

      #test if integer is a prime number
      def testPrim(self, integer):
      if integer >= 1:
      for i in range(2, integer // 2):
      if (integer % i) == 0:
      print(f"{integer} is not a prime number")
      print(f'{integer} is a prime number')

      #test if the number between the given integers are prime number
      def testPrims(self, integer, another_integer):
      if integer < another_integer:
      for i in range(integer, another_integer + 1):
      for j in range(2, i):
      if (i % j) == 0:
      print(f"{i} is not a prime number")
      print(f"{i} is a prime number")

      #multiplication table of a given integer
      def tableMult(self, integer):
      print(f"Multiplication Table of {integer}")
      for i in range(1,11):
      print(f"{integer} x {i} = {integer * i} ")

      #multiplication tables 1-9
      def allTableMult(self):
      for i in range(1,11):
      print(f"Multiplication table of {i}")
      for j in range(1, 11):
      print(f'{j} x {i} = {j * i}')

      #list divisor of a number
      def listDiV(self, n):
      LDiv = []
      for i in range(1, int(math.sqrt(n)) + 1):
      if n % i == 0:
      yield i
      if i * i != n:
      for divisor in reversed(LDiv):
      yield divisor

      #prime divisor of a list
      def listDivPrim(self, integer):
      lst = []
      for i in range(1, int(math.sqrt(integer) + 1)):
      if integer % i == 0:
      if i * i != integer:
      lst.append(integer // i)
      for k in lst:
      if k >= 1:
      for h in range(2, k):
      if k % h == 0:
      #print(f"{k} is not a prime number")
      print(f"Prime Divisor of {integer}: {k}")

      fact = Computation()
      print(f"Factorial: {fact.factorial(4)}")
      print(f'Sum of a given integer: {fact.Sum(5)}')
      print("Test if a number is prime or not:")
      print("Test if two numbers are prime number between them: ")
      print("Display the multiplication table of a given integer")
      print("Display the multiplication table 1-10")
      print("Display the divisor of a given integer")
      print("Show the prime divisor of a given integer")

  2. Replies
    1. import math
      class Circle:
      def __init__(self,a,b,r):
      self.a = a
      self.b = b
      self.r = r
      def area(self):
      return (3.14 * self.r * self.r)

      def perimeter(self):
      return (2 * 3.14 * self.r)

      def to_check(self, x,y):
      self.d = math.sqrt((x-self.a)+(y-self.b))
      if self.d < self.r :
      print("the point x,y belongs inside the circle", x, y)
      elif self.d > self.r :
      print("the point x,y belongs outside the circle", x, y)
      print("the points are on the circle", x,y)

      c1 = Circle(0,1,2)

      Will really appreciate your views on this

    2. Here is the solution of Exercise 44:

  3. Replies
    1. import math

      class Geometry:

      def __init__(self):

      def distance(self,a,b):
      return math.sqrt((b[0]-a[0])**2 + (b[1]-a[1])**2)

      def middle(self,a,b):
      return ((a[0]+b[0])/2),((a[1]+b[1])/2)

      def triangle_perimeter(self,a,b,c):
      return a+b+c

      def iscoceles(self,side_a,side_b,base):
      if side_a == side_b:
      return True
      return False
      length = Geometry()
      print (length.iscoceles(3,3,2))

  4. Given a string of alphabets from the user, you need to encrypt the string by the
    position number of the string, such that each number should be separated by $
    For example let’s say the string is “ Hello World”
    The output should be $8$5$12$12$15$ $23$15$18$12$4$


Learn Python For Beginners

Category Of Mobile Courses

Actualités (644) Adsense (1) Affiliation (1) Algebraic Topology (2) Algorithmic (1) all-news (30) Android (5) Android App (8) Android app without code (4) Android Apps (256) Android Development (4) Android download (2) Android OS (3) AngularJS (1) Automata theory and formal language (5) Bootstrap CSS (1) C programming (5) Category and Functor (8) CMS (3) Computer Glossary (18) Create Mobile App With Ionic Framework (2) CSS (2) CSS-Cascading-Style-Sheets (4) Developpement Java (13) Differential Geometry (1) Django-Python-Framework (15) dropshiping (26) Earn Money by Internet (4) Emplois (23) Framework php (2) Fraud (2) Github (2) HTML (9) IT News (3) Java For Beginners (10) Javascript (12) Kotlin Programming Language (8) Kotlin For Mobile Android (1) Linux Download (2) Marketing (5) Mobile (3) Mobile Courses (4) Mobile Marketing (4) MoneyGram (1) News (721) Node.js (5) Open Source (1) Photoshop (1) Protect Computer (1) Python (37) Python BeautifulSoup (1) Python For Data Science (2) Python PyQt (13) Python Reference (1) Python Source Code (10) Python-Books (6) Python-DVD-Training (1) Python-Exercises (305) Python-Framework (1) Python-IDE (1) Python-Kivy-Framework (2) Python-Modules (1) Python-pdf (2) Python-pyQt (1) python-temp (3) Référencement (2) Script PHP (2) Security (6) SEO (1) Snipping Tool: Faq (1) Social Networks (1) Source Code (4) Statistics With SPSS (2) Surveillance Software (1) Travail à domicile (6) Tutoriels php en vidéos (2) Tutoriels-MySql (6) tutoriels-php (19) Utilitaires (1) VPS (1) Web Hosting (1) Webcam (1) Webmarketing (11) Western Union (1) Windows 10 (1) Windows 7 (4) Windows 7 Faq (2) Windows 8 (1) Windows Accessories (1) Windows Download (8) Windows Drivers (1) Windows Fonts (1) Windows Power Shell (2) Windows Registry (2) Windows Security (18) Windows Software (2) Windows Spyware (2) Windows utilities (3) Windows Virus (2) Windows Vista (3) Windows Wireless (1) Windows xp (1) Wordpress (1)

Sample text

Sample Text

Blogger Templates