0% found this document useful (0 votes)
22 views18 pages

60 Corrected Exercises in Python & OOP

This document contains the description and solution of numerous programming exercises in Python and object-oriented programming. The exercises cover various concepts such as loops, arrays, classes, and methods.
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)
22 views18 pages

60 Corrected Exercises in Python & OOP

This document contains the description and solution of numerous programming exercises in Python and object-oriented programming. The exercises cover various concepts such as loops, arrays, classes, and methods.
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/ 18

TICKER ALGORITHM ALGORITHM ALGORITHM

Home Privacy Policy Contact Us

DATABASE PYTHON ALGORITHM (COURSE) ALGORITHM (EXERCISES) FUNCTIONS IN ALGORITHM C (EXERCISES) C (COURSE) JAVA 

OOP IN JAVA C++ OOP IN C++ MINI-PROJECTS C# LANGUAGE

HomePython 60 Corrected Exercises in Python & OOP

byThe path to programming December 29, 2022

SOCIAL PLUGIN

CATEGORIES

Exercise 1
Write a Python program that displays the message Hello.

(Solution)

Exercise 2
Write a Python program to input two numbers and display their product.

(Solution)

Exercise 3
Write a Python program that allows exchanging the contents of two integers A and B input by
the user. and display these integers after the exchange.

(Solution)
Exercise 4

Write a Python program that allows to display whether an integer entered from the keyboard is even
or odd.

(Solution)

Exercise 5
Write a Python program that displays the largest of three integers entered via the keyboard.

(Solution)

Exercise 6
Write a Python program that allows evaluating a grade entered from the keyboard (if the grade is
greater than 10 then it is validated otherwise not validated (Note: the grade is between 0 and 20).

Solution

Exercise 7
Write a Python program that asks the user for two numbers m and n and then informs them if
the product of these two numbers is positive or negative. We include in the program the case where
the product can be null.

(Solution)

Exercise 8

Write a Python program that calculates the absolute value of an integer entered by
the user.

(Solution)
Exercise 9
Write a Python program that calculates the average of three integers entered by
the user.

(Solution)

Exercise 10
A store offers its customers a 15% discount for purchase amounts exceeding
200 dh. Write a Python program to input the total price excluding tax and to calculate the amount.
TTC taking into account the discount and VAT=20%.

(Solution)

Exercise 11
The photocopy center charges 0.25 DH for the first 10 photocopies, 0.20 DH for the
twenty following and 0.10 DH for more than twenty. Write a Python program that asks for
the user to enter the number of photocopies made and display the corresponding invoice.

Solution

Exercise 12
Write a Python program that asks for a child's age and allows informing of their category
Knowing that the categories are the following:
chick of 6 to 7 years old
student aged 8 to 9 years
minimum of 10 to 11 years old
cadet after 12 years

(Solution)

Exercise 13
Write a Python program to display the month in words according to the number entered.
keyboard. ( If the user types 1 the program displays January, if 2 displays February, if 3 displays March...
).

(Solution)

Exercise 14
Write a Python program that displays the message 'Good evening' 10 times. Using the
while loop.

(Solution)

Exercise 15
Write a Python program to calculate the sum S = 1 + 2 + 3 + ... + 10 using a loop.
while.

(Solution)

Exercise 16
Write a Python program to calculate the sum S=1+2+3+...+ N, where N is entered by
the user. Using the while loop.

(Solution)

Exercise 17
Write a Python program that displays the message 'hello' 10 times. Using
for loop.

(Solution)
Exercise 18
Write a Python program that allows you to calculate the sum S=1+2+3+...+ 10. Using the
for loop.

(Solution)

Exercise 19
Write a Python program that calculates the sum S=1+2+3+4+….+ N. where N is entered.
keyboard by theuser.Usingthe for loop.

(Solution)

Exercise 20
Write a Python program that displays the multiplication table of 5. Using the
For loop.

(Solution)

Exercise 21
Write a Python program that allows displaying the multiplication table of an integer entered by the user.
the user, Using the for loop.

(Solution)

Exercise 22
Write a Python program, enter two numbers from the user and find the greatest.
common divisor using the for loop.

(Solution)

Exercise 23
Write a Python program to enter a number and check if the number is perfect or not.
A perfect number is a positive integer that is equal to the sum of its proper positive divisors.
For example: 6 is the first perfect number
The appropriate divisors of 6 are 1, 2, 3.
Sum of its proper divisors = 1 + 2 + 3 = 6.
Therefore, 6 is a perfect number.

(Solution)

Exercise 24
Write a Python program to input a number and calculate its factorial using a loop.
for.

The factorial of a number 'n' is the product of all positive integers less than or equal to n. It is
noted n!
For example, factorial of 5! = 1*2*3*4*5 = 120.

Solution
Exercise 25
Write a Python program to display all odd numbers from 1 to n using a loop.
for and while.

(Solution)

Exercise 26
Write a Python program to enter a number from the user and count the number of
Find the digits in the given integer using a loop.

(Solution)

Exercise 27
Write a Python program to input a number from the user and find the first and the
last digit of a number using a loop.

(Solution)

Exercise 28
Write a Python program that allows reversing the digits of an integer N entered by the user.
for example N=35672 the displayed result should be 27653.

(Solution)

Exercise 29
Write a Python program to input a number and calculate the sum of its digits.
using the for loop.

(Solution)

Exercise 30
Write a Python program to input the user's number and check that the number is
palindrome or not, using a loop.

(Solution)
Exercise 31
Write a Python program to declare and initialize an array, then input its elements into
start from the user and display the table.

(Solution)

Exercise 32
Write a Python program to declare an array, then input its elements by the user
and remove all negative elements.

(Solution)

Exercise 33
Write a Python program to declare an array, then enter its elements from
the user and find the sum of the elements of the array.

(Solution)

Exercise 34
Write a Python program to declare an array, and then input its elements from
The user will search for the maximum and minimum elements in the array.

(Solution)

Exercise 35
Write a Python program to declare an array, then input its elements from
the user to find the largest and second largest element in this array.

(Solution)

Exercise 36
Write a Python program to declare an array, then input its elements from
the user and count the number of even and odd elements in this array.

(Solution)
Exercise 37
Write a Python program to declare two arrays, then enter the elements of the first one.
user table and copy all its elements into the second table.

(Solution)

Exercise 38
Create a Python program that creates and initializes an array, then inserts an element at the position
specified in this table (from 0 to N-1).
To insert a new element into the array, move the elements from the insertion position.
give towards a position to the right.

(Solution)

Exercise 39
Create a Python program that creates and initializes an array, then removes an element from it.
array at the specified position (from 0 to N-1).
To remove an element from the array, move the elements just after the given position to
a position to the left and reduce the size of the table.

(Solution)

Exercise 40
Create a Python program that creates and initializes an array, then finds the frequency of each
element of this table.

(Solution)

Exercise 41
Create a Python program that creates and initializes an array, then displays all unique elements.
of this painting
Idea: use a frequency table.

(Solution)

Exercise 42
Create a Python program that creates and initializes an array, then counts the duplicate elements.
in this table.

Solution

Exercise 43
Create a Python program that creates and initializes an array, then removes duplicate elements.
in this table.

(Solution)

Exercise 44

Create a Python program that creates and initializes an array, then reverses this array without using.
an additional table.

(Solution)

Exercise 45
Write a Python program that allows you to calculate the sum:

S = 1^1 + 2^2 + 3^3 +........+ n^n

*** Solution ****

S=0

n=int(input("Give an integer:"))
for i in range(1, n + 1):

S = S + i ** i

print("the sum is: " , S)

OOP in Python

Exercise 46 class Rectangle

Write in Python a class 'Rectangle' with two variables 'a' and 'b' and a function
member "surface()" that will return the area of the rectangle.

Corrected

class Rectangle:
def __init__ (self,a=0,b=0):
self.a=a
self.b = b
def surface(self):
return self.a * self.b

r1 = Rectangle();
r2 = Rectangle (5,4);
print("the area is:")r1.surface())
print("the surface is:" ,r2.surface());

Exercise 47: Sum class

Write in Python a class 'Sum' having two variables 'n1' and 'n2' and a
member function 'sum()' which calculates the sum. In the main method
ask the user to enter two integers and pass them to the default constructor
from the class 'Sum' and display the result of the addition of the two numbers.

Corrected

class Sum:
def __init__(self, nbr1=0, nbr2=0):
nbr1
self.n2=nbr2

def som(self):
return n1 + n2

n1 = int(input("Enter N1:"))
n2 = int(input("Enter N1:"))
obj = Sum(n1,n2);
print("The result of the addition is:",obj.som())

Exercise 48: Student Class

Write a Python class called 'Student' with the following members:


name: (of type char),
float type
calc_moy() : calculates the average grade.
retrieve() : retrieve the name and the average score.
The main program asks the user to enter the name and the grades of a
student. and indicates their name and the average grade.

Corrected
class Student:
def __init__(self,name,grade1,grade2):
self.namename
self.notenote1
self.note2 = note2

def calc_avg(self):
return (self.note1 +self.note2)/2

def a icher (self):


Student:self.name:self.calc_moy())

Enter the name:


Enter the grade 1:
note2 = int(input("Enter grade 2: "))
Student (name, score1, score2)
E.a icher()

Exercise 49: point class


Create a Python class Point to manipulate a point in a plane.
will foresee

A point is defined by its coordinates x and y (private members)

the builders

3) a member function moves performing a translation defined by its two


arguments dx and dy (double)

4) a member function that simply displays the Cartesian coordinates of


point.

5) a member function 'saisir' that simply inputs the Cartesian coordinates of the
point.

6) a member function distance calculating the distance between two points.

7) a member function middle giving the midpoint of a segment.

8) a small test program (main) managing the point class.

Corrected

from math import *

class Point:
def __init__(self,a=0,b=0):
self.x=a
self.y=b
def get_x(self):
return self.x
def get_y(self):
return self.y

def set_x(self,a):
self.x=a

def set_y(self, b):


self.y = b

def move(self, dx, dy):


self.set_x(self.get_x()+dx)
self.set_y(self.get_y()+dy)
def a iche(self):
print("x=",self.get_x())
print("y=",self.get_y())

def enter(self):
give the coordinates
self.x = int(input("x = "))
int(input("y = "))

def distance (self,p):


x1=(self.get_x()-p.getself.get_x()-p.get_x());
x2=(self.get_y()-p.getself.get_y()-p.get_y());
d=sqrt(x1+x2)
return d

def environment(self, p):


p1 = Point();
p1.x=(self.get_x()+p.get_x())/2
p1.y=(self.get_y()+p.get_y())/2
return p1

p = Point(1,1)
x = Point(5,5)
c = Point()
p.a iche()
p.move(5,5)
page();
print("the distance px is:")p.distance(x));
p.environment(x)
the middle of [px] is: (c.get"c.get_y(),")")

Exercise 50: Account class


Write a program in Python that simulates the management of a simple bank account. The
an account is created with an initial balance. It is possible to deposit and withdraw funds,
to add interest and to know the current balance. This should be implemented in
a class named Account which includes:

1) A default constructor that sets the initial balance to zero.


2) A constructor that accepts an initial balance as a parameter.
3) A getBalance function that returns the current balance.
4) A deposit method to deposit a specified amount.
5) A method to withdraw a specified amount.
6) A method add_Interest to add interest to the account.
The add_Interest method takes the interest rate as a parameter and modifies the
account balance in balance * (1 + interest rate).

Corrected
class Account:
def __init__(self, balance=0):
self.balancebalance

def getBalance(self):
returnself.balance

def deposit(self, amount):


self.balance+= amount

def withdraw(self, amount):


self.balance-= amount

def add_Interest (self, rate):


self.balance= self.balance(1 + rate)
account1 = Account()
Account(3000)
account1.deposit(100)
account2.withdraw(1000)
account1.addInterest (0.3)
print(account1.getBalance())
print(account2.getBalance())

Exercise 51: Time class


Create in Python a class called Time, which has members of type int such as
hours, minutes, and seconds. (make them private)
A constructor must initialize these data to 0.
Another constructor should initialize it to fixed values.
A member function should display it in the format 17h 59min 59s.
4) Another function to return the data of each member, name them.
getHours
5) A member function must add two objects of type Time passed as arguments.

Corrected

class Temps:
def setTemps(self, h, m, s):
self.hours= h
self.minutes= m
self.seconds= s

def __init__ (self,h=0,m=0,s=0):


self.setTemps(h,m,s)

def getHours(self):
returnself.hours
def getMin(self) :
returnself.minutes
def getSec(self) :
returnself.seconds

def getTemps(self):
print(self.hourshself.minutesminself.seconds,"s")

def addTime(self, t1, t2):


self.seconds= t1.seconds+ t2.seconds
self.minutes= t1.minutes+ t2.minutes+ (int(self.seconds/60))
self.hours= t1.hours+ t2.hours+ (int(self.minutes/60))
self.minutes%= 60
self.seconds%= 60

t1 = Time(4, 43, 59)


t2 = Time(1,20,32)
t3 = Time()
t1.getTemps()
t2.getTemps()
t3.addTime(t1, t2)
t3.getTemps()

Exercise 52: Rectangle Class


Write a Python program using a rectangle class whose constructor takes
two parameters, width and height, and which offers the following functions:

1) calculation of the perimeter


2) calculation of the area

3) display

as well as the trivial accessors and mutators (reading and modifying the width and
the height).

Corrected

class Rectangle:
def __init__(self, L, h):
self.width= L
self.height= h
def getWidth(self):
return width
def getHeight(self):
return height
def perimeter(self) :
return 2*(self.width+ self.height)
def surface(self):
returnself.width* self.height
def setWidth(self, newWidth):
self.width= newWidth
def setHeight(self, newHeight):
self.height= newHeight

def gather(self):
print("the length :",self.height)
print("the width :" ,self.width)

R= Rectangle (5,4)
R.a icher()
print("the surface is"R.surface());
print("the perimeter is",R.perimeter())

Exercise 53: Inheritance


Write a program in Python that defines a class called Shape with a
constructor that gives value to width(x) and height(y). Define the method
area() in the two subclasses Triangle and Rectangle, which calculate the area. In the
main method, define two variables, a triangle and a rectangle, then
call the area() function in these two variables.

Note that:

The area of the triangle is = width * height / 2

The area of the rectangle is = width * height.

Corrected
class Shape:
def __init__(self,x=0,y=0):
self.x = x
self.y = y

class Rectangle (Shape):


def __init__(self,x=0,y=0):
Form.__init__(self, x, y)

def air(self):
return (self.x * self.y)

class Triangle (Shape):


def __init__(self, x=0, y=0):
Form.__init__(self,x,y)
def air(self):
return (self.x * self.y / 2)

R = Rectangle (2,3)
T = Triangle (2,3)
R1 = Rectangle()
print(R.aire())
Invalid inputT.air())
Invalid inputR1.air())

Exercise 54: Rectangle Class


1) Write a Rectangle class in Python to construct a rectangle.
endowed with length and width attributes.
2) Create a method Perimetre() to calculate the perimeter of the rectangle and
a Surface() method for calculating the area of the rectangle
3) Create the getters and setters.
4) Create a subclass Parallelepiped inheriting from the Rectangle class and additionally equipped
of a height attribute and another method Volume() for calculating the volume
of the Parallelepiped.

Response

#coding: utf-8
class Rectangle:
def __init__(self, length, width):
self.lengthlength
self.widthwidth

Method that calculates the perimeter


def Perimeter(self):
return 2*(self.length+ self.width)

Method that calculates the area


def Surface(self):
returnself.length*self.width

class Parallelepiped(Rectangle):
def __init__(self, length, width, height):
Rectangle.__init__(self,length,width)
self.height= height

method that calculates the volume


def Volume(self):
returnself.length*self.width*self.height

Rectangle(7, 5)
Parallelepiped(7, 5, 2)
The perimeter of my rectangle is:myRectangle.Perimeter())
The area of my rectangle is:myRectangle.Surface())
print("The volume of my parallelepiped is :" ,myParallelepiped.Volume())

Exercise 55: Bank account


1) Create a Python class named BankAccount that represents a bank account,
accountNumber (numeric type)
account of the string type), balance.
2) Create a constructor with parameters: accountNumber, name, balance.
3) Create a method Deposit() that manages deposits.
4) Create a method Withdraw() that manages withdrawals.
5) Create a method Agios() that applies the agios at a rate of 5%.
of the balance

6) Create a method display() to show the details of the account


7) Provide the complete code of the BankAccount class.
Response

class BankAccount:
def __init__(self, idNumber, nameSurname, balance):
self.idNumberidNumber
self.nameSurnamefirstNameLastName
self.balancebalance

deposit(self, money):
self.balance= self.balance+ silver

def withdrawal(self, amount):


if(self.balance< silver):
Unable to perform the operation. Insufficient balance!
else:
self.balance= self.balancesilver

def agios(self):
self balance=self.balance95/100

def a icher(self):
Account number:self.idNumber)
Print("Name & Surname :" ,self.nameSurname)
print(" Balance :"self.balanceDH

monCompte = CompteBancaire(16168891, " Mohamed Rachid",22300)


myAccount.deposit1500
myAccount.withdrawal(24000)
#myAccount.interestCharges()
myAccount.display()

Exercise 56: Class Circle


1) Define a Circle class that allows creating a circle C(O,r) with center O(a,b) and
rayon r using the constructor:
2) Define a method Surface() of the class that calculates the area of the circle
3) Define a method Perimeter() in the class that allows calculating the perimeter of
circle
4) Define a method testMembership() of the class that allows testing if a point
A(x,y) belongs or does not belong to the circle C(O,r).

Response

#coding: utf-8
from math import *
class Circle:
def __init__(self, a, b, r):
self.a = a
self.b = b
self.r = r

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

def surface(self):
return pi*self.r**2

def formEquation(self,x,y):
return (x-self.a)**2 + (y-self.b)**2 -self.r**2
def test_membership(self, x, y):
if(self.formEquation(x,y)==0):
the point: (
else:
The point: (

Instantiation
C = Circle(1,2,1)

print("the perimeter of circle C is:",C.perimeter())


print("the surface of the circle C is:" ,C.surface())
C.testbelonging(1,1)

Exercise 57: Arithmetic calculation


1) Create a class Calculation with a default constructor (without parameters)
allowing to perform various calculations on integers.
2) Create within the Calcul class a method named Factorielle() that allows
calculate the factorial of an integer. Test the method by creating an instance on the
class.
3) Create a method named Sum() within the class Calcul allowing to
calculate the sum of the first n integers: 1 + 2 + 3 + .. + n. Test the method.
4) Create within the Calcul class a method named testPrim() that allows testing
the primality of a given integer. Test the method.
5) Create within the class Calcul a method named testPrims() allowing to
test if two numbers are coprime.

6) Create a method tableMult() that creates and displays the multiplication table of an integer
given. Then create a method allTablesMult() to display all the
multiplication tables of the integers 1, 2, 3, ..., 9.
7) Create a method listDiv() that retrieves all the divisors of a given integer on
a list Ldiv. Create another method listDivPrim() that retrieves all the divisors
firsts of a given integer.

Response

#coding: utf-8
class Calcul:
def __init__(self):
pass
Factorial
def factorial(self, n):
j=1
for i in range(1,n+1):
j = j*i
return j
Sum of the first n numbers
def sum(self, n):
j=1
for i in range(1,n+1):
j=j+i
return j
#---Primality test of a number------------
def testPrim(self, n):
j=0
for i in range(1, n+1):
if(n % i == 0):
j=j+1
if(j == 2):
return True
else:
return False
# ---Primality test of two integers------------
def testprims(self, n, m):
divCommun = 0
for i in range(1, n + 1):
if (n%i == 0 and m%i == 0):
divCommun = divCommun + 1
if divCommun == 1:
The numbers
else:
The numbers

Multiplication Table
def tableMult(self, k):
for i in range(1,10):
print(i, ' x ', k, ' = ', i * k)

All the multiplication tables of the numbers 1, 2, .., 9


def allTables(self):
for k in range(1,10):
the multiplication table of :
for i in range(1,10):
print(i, ' x ', k, ' = ', i * k)

List of divisors of an integer


def listDiv(self, n):
initialization of the list of divisors
lDiv = []
for i in range(1, n + 1):
if ( n % i == 0):
lDiv.append(i)
return lDiv

# ------list of prime divisors of an integer----------------


def listDivPrim(self, n):
initialization of the list of divisors
lDiv = []
for i in range(1, n + 1):
if ( n%i == 0 andself.testPrim(i):
lDiv.append(i)
return lDiv

Example Instantiation
Cal = Calcul()
Cal.testprims(13, 7)
List of divisors of 18 :Cal.listDiv(18))
List of prime divisors of 18 :Cal.listDivPrim(18))
Cal.allTables()

Exercise 58
Code a class myString to equip strings with methods
append() and pop() perform the same operations as those of lists. For example, if we
create strings by instantiation s1 = myString("Hello") and s2 = "bonjour", and it
apply the methods:
Invalid inputs1.appendHello world !
Invalid inputs2.popHello

Response

class myString:
def __init__(self, s):
self.s = s
def append(self,x):
self.s = self.s + x
return self.s

def pop(self,i):
s1 = self.s[0:i]
s2 = self.s[i+1:len(self.s)]
return s1+s2
def modifier(self, i):
pass

Test the class


S = myString("hello")
Invalid inputS.popa iche 'hello'
print(S.appendhello world !

Exercise 59
1. Define a class Book with the following attributes: Title, Author (Full Name), Price.
2. Define a constructor with attributes: Title, Author, Price.
3. Define the View() method to display the information of a Book object instance.
4. Write a program to test the Book class.

Response

#coding: utf-8
Question 1
class Book:
Question 2
def __init__(self, Title, Author, Price):
self.TitleTitle
self.AuthorAuthor
self.PricePrice

Question 3
def view(self):
return ("Book Title: " ,self.TitleBook Authorself.AuthorBook Price
, self.Price)

Question 4
MyBook = Book("Python" , "Mohamed" , "23 Dh")
print(MyBook.view())

Exercise 60: Geometry Class


Write a Python class named Geometry with a default constructor without
parameters.
1) Add a method named distance() to the geometry class that allows calculating
the distance between two points
A = (a1, a2), B = (b1, b2) (with the convention: a point is identified by its)
coordinates M = (xM, yM)
2) Add a method named middle() to the geometry class that allows for
determine the midpoint of a bipoint (A, B).
3) Add a method named trianglePerimeter() to the geometry class that allows
to calculate the perimeter of a triangle ABC.
4) Add a method named triangleIsoscel() that returns True if the triangle is
isoceles and False otherwise.
Tags algorithm databases C# C++ digital development computer development JAVA
C Language OOP OOP Programming Python

Facebook Twitter

These posts might interest you

ALGORITHM ALGORITHM ALGORITHM

March 14, 2023 February 15, 2023 December 29, 2022

SAVE A COMMENT

2 Comments

MELATA
March 8, 2023 at 16:39

Please, here you have only provided corrected exercises. We also want lessons to understand.

Respond Delete

Hachimi Mustapha
December 7, 2023 at 11:30

thank you very much for your efforts

Respond Delete

Copyright © 2023Moroccan Code Home Privacy Policy Contact Us

You might also like