60 Corrected Exercises in Python & OOP
60 Corrected Exercises in Python & OOP
DATABASE PYTHON ALGORITHM (COURSE) ALGORITHM (EXERCISES) FUNCTIONS IN ALGORITHM C (EXERCISES) C (COURSE) JAVA
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=0
n=int(input("Give an integer:"))
for i in range(1, n + 1):
S = S + i ** i
OOP in Python
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());
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())
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
the builders
5) a member function 'saisir' that simply inputs the Cartesian coordinates of the
point.
Corrected
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 enter(self):
give the coordinates
self.x = int(input("x = "))
int(input("y = "))
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(),")")
Corrected
class Account:
def __init__(self, balance=0):
self.balancebalance
def getBalance(self):
returnself.balance
Corrected
class Temps:
def setTemps(self, h, m, s):
self.hours= h
self.minutes= m
self.seconds= 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")
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())
Note that:
Corrected
class Shape:
def __init__(self,x=0,y=0):
self.x = x
self.y = y
def air(self):
return (self.x * self.y)
R = Rectangle (2,3)
T = Triangle (2,3)
R1 = Rectangle()
print(R.aire())
Invalid inputT.air())
Invalid inputR1.air())
Response
#coding: utf-8
class Rectangle:
def __init__(self, length, width):
self.lengthlength
self.widthwidth
class Parallelepiped(Rectangle):
def __init__(self, length, width, height):
Rectangle.__init__(self,length,width)
self.height= 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())
class BankAccount:
def __init__(self, idNumber, nameSurname, balance):
self.idNumberidNumber
self.nameSurnamefirstNameLastName
self.balancebalance
deposit(self, money):
self.balance= self.balance+ silver
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
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)
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)
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
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())
Facebook Twitter
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
Respond Delete