0% found this document useful (0 votes)
8 views7 pages

Python OOP Exercises for Beginners

The document outlines exercises for a Computer Science course focused on Object-Oriented Programming in Python. It includes tasks to create classes such as Point, Rectangle, Time, BankAccount, Car, Person, Worker, Scientist, and others, each with specific attributes and methods. Additionally, it covers concepts like class inheritance, exception handling, and the implementation of various functionalities like an address book and flight management.

Translated by

ScribdTranslations
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)
8 views7 pages

Python OOP Exercises for Beginners

The document outlines exercises for a Computer Science course focused on Object-Oriented Programming in Python. It includes tasks to create classes such as Point, Rectangle, Time, BankAccount, Car, Person, Worker, Scientist, and others, each with specific attributes and methods. Additionally, it covers concepts like class inheritance, exception handling, and the implementation of various functionalities like an address book and flight management.

Translated by

ScribdTranslations
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

Computer Science–2thYear IPEIN

Chapter 2

TP. Object-Oriented Programming in Python


Exercise 1.
1. Create a Python class named 'Point' defined by two instance attributes x = 3.0 and y = 4.0
representing the coordinates of a point.
2. Create an instance of the Point class.
3. Define a method display(self) that allows displaying a point.
4. Define a Python class named 'Rectangle' defined by a point that represents the position of the corner.
top left of the rectangle and its size (width and height).
5. Create an instance of the Rectangle class where the value of its top left corner is a Point (12.0;
27.0), its width = 50.0 and its height = 35.0.
6. Create a Python function (outside of the Rectangle class) named findCenter that can be called
with a Rectangle type argument and returns a Point type object, which will contain the coordinates of the
center of the rectangle.
[Link] this function using the defined object as an argument and display the found center.
8. Change the size (height and width) of the box object without changing its position (corner);

Exercise 2.
1. Define a Python class named 'Time' defined by instance variables to store the hours,
hours:minutes:seconds. Example: (12:32:45).
2. Create an object of type Time.
3. Create a function show_time(t) that is used to visualize the attributes of an object of the Time class.
4. Redefine the method affiche_heure (self), inside the class Time. The first parameter "self" is
mandatory, because it represents the instance to which the method will be associated.
5. Create an object of type Time now and test the new method on this object.

Exercise 3.
Define a BankAccount class (), which allows the instantiation of objects such as account1, account2, etc.
The constructor of this class will initialize two attributes name and balance, with the default values 'Salim' and 1000.
Three other methods will be defined:
[Link](self, somme) will allow to add a certain amount to the balance;
[Link](self, somme) will allow to withdraw a certain amount from the balance;
c.__repr__(self) will display the name of the account holder and the balance of their account.

Examples of how to use this class:


account1 = BankAccount('Sami', 800)
[Link](350)
[Link](200)
account1
Sami's bank account balance is 950 Dinars.
>>> account2 = BankAccount()
>>> [Link](25)
account2
Salim's bank account balance is 1025 Dinars.

anis_saied@[Link] Page 1 of 7 [Link]


Computer Science–2ème Year IPEIN
Exercise 4.
Define a Car class() that allows instantiating objects that replicate the behavior of cars.
automobiles. The manufacturer of this class initializes the following instance attributes with default values
indiqués :marque = 'Ford', couleur = 'rouge', pilote = 'personne', vitesse = 0.
When we instantiate a new Car object, we will be able to choose its brand and color, but not its speed.
he is your driver.
Define the following methods:
1.driver_choice (self) will allow to designate (or change) the name of the driver.
[Link] (self, rate, duration) will allow to vary the speed of the car. The variation of the speed of the
The car will be equal to the product: rate × duration. For example, if the car accelerates at a rate of 1.3 m/s for
20 seconds, his speed gain must be equal to 26 m/s. Negative rates will be accepted (which will allow
decelerate). The change in speed will not be allowed if the driver is "person".
3.show_all (self) allows displaying the current properties of the car, namely its brand,
its color, the name of its driver, and its speed.
4. Define a special method __str__(self) that serves the same purpose as affiche_tout().

Examples of using this class:

a1 = Car('Peugeot', 'blue')
>>> a2 = Voiture(couleur='verte')
a3 = Car('Mercedes')
>>> a1 = Car('Peugeot', 'blue')
>>> a1.driver_choice("Ramzi")
>>> a2.driver_choice("Safa")
>>> [Link](1.8, 12)
[Link](1.9, 11)
This car has no driver
>>> a2.display_all()
Ford driven by Safa, speed = 21.6 m/s
>>> a3.display_all()
Red Mercedes driven by no one, speed = 0 m/s
>>> print(a3)
Red Mercedes driven by no one, speed = 0 m/s

Exercise 5.
Classes are often used to model objects in the real world. We can represent
the data about a person in a program through a Person class, containing the person's name,
his name, his phone number, and his email. A __str__ method can print the data of the
nobody.
Examples:
>>> amir = Personne('Ben Salem', 'Amir', '55593581', "amirbs@[Link]")
>>> print(amir)
Ben Salem, Amir -- Telephone: 55593581 -- Email: "amirbs@[Link]"
>>> mariem = Personne('Abassi', 'Mariem', '55519403',"mariem12@[Link]")
>>> print(mariem)
Abassi, Mariem -- Telephone : 55519403 -- Email :"mariem12@[Link]"
Work to do: Implement the Person class.

anis_saied@[Link] Page 2 of 7 [Link]


Computer Science–2thYear IPEIN
A worker is a person who has a job. In a program, a worker is naturally
represented as a Worker class derived from the Person class, because a worker is a
person, that is to say, we have a relationship is a. The Worker class extends the Person class with
additional data, for example the name of the company, the address of the company and the number of
work phone. The print function (the special method __str__) must be modified to
consequence.
Travail à faire: Mettre en œuvre cette classe Travailleur.

A scientist is a special type of worker. The Scientist class can thus be derived from the class
Worker. Add data on the scientific discipline (physics, chemistry, mathematics,
computer science, ...). One can also add the type of scientist: theoretical, experimental, or computational. The
the value of such a type attribute should not be limited to a single category, as a scientist can be
classified as, for example, both experimental and computer-based (that is, you can represent the
value in the form of a list or a tuple.
Work to be done: Implement the Scientist class.

4. Finally, create a main demonstration program where you create and print instances of classes.
Person, Worker and Scientist. Print the content of the attributes of each instance.

Exercise 6.
In this exercise, you will build an address book using the Person class defined in the
the previous exercise to record your contacts (friends, family, ...). Each entry in the address book will be
an instance of the Person class.
The address book should allow you to search for and return information about your contacts.
Work to be done:
Create a class AddressBook containing the following methods:
1. The constructor method __init__
2. The __str__ printing method
3. A method called add_contact that allows you to add a person to your address book.
4. A method search_contact that searches for a contact by their name among the registered people in
your address book and display in a new line each contact with the specified name. This
method must accept two arguments:
• A mandatory argument: the name of the contact to search.
• A second optional argument: the contact's first name, allowing to narrow down the result if there are multiple.
contacts have the same name.
This is an example that shows you how your class should work after the implementation of these two.
methods.
For example, your address book contains the entries 'Ali Ben Salem' and his sister 'Sana Ben Salem':
>>> a = AddressBook()
>>> a.add_contact(Person('Ben Salem', 'Ali', ... ))
>>> a.add_contact(Person('Ben Salem', 'Sana', ... ))
>>> a.find_contact('Ben Salem')
Ben Salem, Ali -- Telephone : ...
Ben Salem, Sana -- Telephone : ...
>>> a.search_contact('Ben Salem', 'Ali')
Ben Salem, Ali -- Telephone : ...

anis_saied@[Link] Page 3 of 7 [Link]


Computer Science–2ème Year IPEIN
Exercise 7.
1. Créer une classeIntervallepossédant une méthode __init__permettant d’initialiserune borne inférieure et
an upper bound for an object of type Interval. Check that the bounds are numeric, positive,
not placed in the correct order, otherwise generate an 'IntervalError' exception displaying
the error message "Error: Invalid bounds!". The type "IntervalError" is a
Exception to define.
2. Indeed, with the checks defined in the __init__ method, it is no longer possible to create a malformed interval.
However, it is still possible for a programmer to write directly a.borne_sup = -2, which will set -
2 in the upper bound of the interval a.
Modify the extent of the attributes lower_limit and upper_limit so that they are only visible from the
methods of the class, but not from the outside.
3. To modify a value of the interval, now write a method in the Interval class.
modif_borne_sup will allow protecting the upper limit by only allowing numbers to be written there.
greater than the lower limit.
4. Add a method modify_lower_bound to the Interval class. Be careful that a negative value does not
could not be recorded.
5. Write two access methods: lire_inf(self) and unlire_sup(self) that will return the boundary values.
6. Write a special method __str__(self) that returns a string indicating the values of the two
endpoints of the interval.
7. Write a special method __contains__(self, val) that tests if a value val belongs to the interval or not.
(this method replaces the 'in' operator).
8. Write a special method __add__(self, other) that returns a new Interval that is the sum of the two.
intervals. Example: [2,5] + [3,4] = [5,9]
9. Write a special method __sub__(self, other) that returns a new Interval resulting from the subtraction of the two.
[a,b]-[c,d]=[a-d,b-c] ; [2,5]-[3,4]=[-2,2]
10. Write a special method __mul__(self, other) that returns a new Interval as the multiplication of the two.
intervals. Example: [2,5] * [3,4] = [6,20]
11. Write a special method __and__(self, other) that returns the intersection of the two intervals. «
None" if their intersection is empty. Example: [2,5]∩[3,6]=[3,5]
12. In the main program:
a. Display the interval ["0.35","0.8"]. What do you notice?
b. Store the interval [1,6] in a variable a and the interval [4,8] in a variable b.
c. Change the value of the upper bound to 5.
[Link] the intersection, sum, difference, and product of the two intervals a and b.
[Link] the intersection of a with the interval [9,11].

Exercise 8:
Let's program a class Vector2d whose objects will model vectors with two real components in a
orthonormal frame (O ; I ; J), graduated with the same unit (OI = OJ = 1 unit). When the mathematician says: "
Let it be the vector ⃗ (3,-2), the Python programmer will say: "u = Vect2d(3,-2)".

1. Program the constructor, responsible for initializing the attributes x and y of the current instance, which is named
By default, x and y will be set to 0.
If I want to add two vectors, I have two solutions. Either I program a mathematical function.
add(v1,v2) outside the class. Or, in a pure object-oriented programming perspective, I
addProgram as an instance method inside the class. Adopt this second solution, for
which the result of the addition with the method will be a new vector.

anis_saied@[Link] Page 4 of 7 [Link]


Information Technology–2thYear IPEIN
3. Program a method that performs multiplication ⃗ of a real by a vector ⃗ The result
it will be a new vector.
4. Program a method to zoom allowing a vector to multiply by parket to be thus permanent.
modified! Make sure to distinguish it from mul_ext.
5. Program a method that asks a vector to return its scalar product with another one.
vector.
6. Deduce a method requiring a vector to return its length.
7. Program an outside function add(v1, v2) that returns the sum.
vectorial1+⃗⃗⃗⃗ . ⃗⃗⃗⃗ 2
Note: In principle, it is impossible to write u + v if u and v are two vectors. But in Python, some ...
special methods are hidden under the operators. If your add method is named __add__, it becomes
possible!
8. In order to test your classVect2d:
a. Create two vectors ⃗ (3,-2) and (4,1)
b. Create a vector=⃗⃗⃗⃗ ⃗ +
c. Check that ⃗ (+ ⃗⃗ ∙⃗ ⃗ = ⃗ )∙ ⃗ + ⃗ ⃗ ∙ ⃗
d. Check that5 (⃗ ∙ ⃗ =) 5 ( ⃗ ∙ ⃗ )

Exercise 9:
In this exercise, we are interested in creating classes to manage the flights of a local airline that
Organize flights between cities. More specifically, we will focus on flight plans between different cities.
Here are the available flights along with the departure time.

1. To create a DirectFlight class that will represent a direct flight between two cities (no layover in a city
intermediate), we must:
[Link] the constructor of this class that has four attributes:
• depetarrqui designates respectively the departure city and the arrival city
• day refers to the day of the week (Monday, Tuesday, ... )
• hour (an integer between 0 and 24 representing the departure time)

[Link] a methodDisplaythat shows a well-formatted string of the form:


This flight departs from 'Tunis' to 'Djerba' on 'Monday' at 9 o'clock.

2. Create a class Flights that will represent all the flights throughout the week using the Direct_Flight class.
To do this, we must:
2.1. Define the constructor of this class with a single attribute that is a list of flights.
2.2. Write a method List_successors that returns a list containing the destination cities from a city of
departure passed as parameter
2.3. Write a method called Belongs that checks whether a city is part of the flight plan, whether as
city of arrival or departure
2.4. Write a methodDisplaythat shows all direct flights

3. Write a main program allowing to:


a. Create a list LV of direct flight objects
Note: it is assumed that the following 3 functions have been defined: Saisie_Jour which returns a valid day,
Input_Time() which returns a valid time and Input_City() which returns a valid city name.
b. Create a Flight object named V from the already created list
c. Display all flights
d. Enter a city that must belong to the flight plan and then calculate and display the list of its successors

anis_saied@[Link] Page 5 of 7 [Link]


Computer Science–2thYear IPEIN
Exercise 10:
The objective of this exercise is the manipulation of sparse polynomials in a single variable. A sparse polynomial is
a polynomial with some coefficients being zero. A polynomial is constructed from monomials. A monomial
is an expression of the form wherea (a ≠ 0) is the coefficient of the monomial andn (n > 0) his degree. A
A monomial is represented by a one-element dictionary where the key is the degree n and the value is the coefficient a.
Example:
The monomial8 2is represented by the dictionary {2:8 }.
A hollow polynomial is then defined as an association of monomials of different degrees.
Examples:
The polynomial− 4+ 8 2 − 5 est représenté par le dictionnaire { 2:8 , 1:-5 , 4 :-1}.
The dictionary {0:1, 5:1, 8:1} represents the polynomial 8+ 5+ 1.

We propose to build the class PolynomeCreux with real coefficients, the skeleton (to be completed) of which is defined
by :
class PlynomeCreux :
Manipulation of single-variable sparse polynomials
def __init__(self):
[Link] = {} # initialization to a null polynomial

def add_monom(self, monome ={}):


"""
This method adds a monomial entered from the keyboard if the parameter
monomial is null or add the named monomial otherwise
"""
if len(monome) == 0 :
#réponse à la question 1

else :
if my monome is not empty
degree = list([Link]())[0] # extraction of the degree
coeff = list([Link]())[0] # extraction of the coefficient
try :
assert degree >= 0
assert type(degre) == int
assert type(coeff) == int or type(coeff) == float
assert len(monome) == 1
[Link](monome) # [Link][degree] = coefficient
except :
Error adding monomial

def degree(self):
#réponse à la question 2

def __call__(self, x0):


#réponse à la question 3

def __add__(self, other): #other is a sparse polynomial
response to question 4

anis_saied@[Link] Page 6 of 7 [Link]


Computer Science–2thYear IPEIN

def __mul__(self, other): #other is a sparse polynomial
#response to question 5

def __str__(self):
response to question 6

def primitive(self):
#réponse à la question 7

Requested work:
Question 1 :
Complete the script of the method add_monome. It is reminded that this method adds a monomial entered to
keyboard (after performing the necessary checks) if the parameter monome is null or add the monomial named monome
otherwise.
Question 2 :
Write the script for the method named degree, which returns the degree of the polynomial.
Question 3:
Write the script for the method named __call__ which returns the value of the polynomial for a given real x0.
Question 4 :
Write the script of the method named __add__, which returns the sum polynomial of two polynomials. Note
no null monomial should appear in the resulting polynomial.
Question 5:
Write the script for the method named __mul__, which returns the product polynomial of two polynomials.
Note: no zero monomial should appear in the resulting polynomial.
Question 6 :
Write the script for the method named __str__, which returns the string representing the expression of the polynomial.
ordered in descending order.
For the polynomial represented by { 4:4, 0:4 , 12:6 , 9:1 , 7 :-1}, the returned string is: "6*x**12 + x**9 - x**7"
+ 4*x**4 + 4
Question 7 :
Write the script of the method, named primitive, which returns the polynomial representing the primitive. It is assumed
that the constant of integration is zero.
Question 8 :
The integral of a hollow polynomial P in x between the limits a and b is defined by: =∫
Write the script for the function named 'integrale' that returns the value of S from a polynomial.
P, of type SparsePolynomial, and integration limits a and b real.

anis_saied@[Link] Page 7 of 7 [Link]

You might also like