0% found this document useful (0 votes)
666 views46 pages

PyLab2 (ch1 5)

The document contains 11 coding problems with sample inputs and outputs. Each problem involves taking user input, performing calculations or conditional checks, and outputting the result. The problems cover concepts like loops, conditional logic, arithmetic operations, and calculating totals.

Uploaded by

Keerthana
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)
666 views46 pages

PyLab2 (ch1 5)

The document contains 11 coding problems with sample inputs and outputs. Each problem involves taking user input, performing calculations or conditional checks, and outputting the result. The problems cover concepts like loops, conditional logic, arithmetic operations, and calculating totals.

Uploaded by

Keerthana
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/ 46

HAARISINFOTECH- LEVEL2 LAB-BOOK

PROBLEM-1:

Write a program that takes a number N as the input, and prints it to the output.

Input Format

The only line contains a single integer.

Output Format

Output the answer in a single line.

CODE:

a = input()

print(a)

Input Output

123 123

PROBLEM-2:

consider a turn to be good if the sum of the numbers on their dice is greater than 6. Given that in a particular turn Chef
and Chefina got X and Y on their respective dice, find whether the turn was good.

Input Format

The first line of input will contain a single integer T, denoting the number of test cases. Each test case contains two
space-separated integers X and Y — the numbers Chef and Chefina got on their respective dice.

Output Format

For each test case, output on a new line, YES, if the turn was good and NO otherwise.

CODE:

T = int(input())

for i in range(T):

a = input()

x = int(a[0])

y = int(a[2])

if(x+y > 6):

print("YES")

1
HAARISINFOTECH- LEVEL2 LAB-BOOK

else:

print("NO")

INPUT:

14

34

42

26

OUTPUT:

NO

YES

NO

YES

PROBLEM-3:

The task is very simple: given two integers A and B, write a program to add these two numbers and output it

Input Format

The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains two Integers A
and B.

Output Format

For each test case, add A and B and display the sum in a new line.

CODE:

T = int(input())

for tc in range(T):

(a, b) = map(int, input().split(' '))

ans = a + b

print(ans)

2
HAARISINFOTECH- LEVEL2 LAB-BOOK

INPUT:

12

100 200

10 40

OUTPUT:

300

50

PROGRAM-4

To take the exam, there are following requirements:

Minimum age limit is X (i.e. Age should be greater than or equal to X). Age should be strictly less than Y.Chef's current
Age is A. Find whether he is currently eligible to take the exam or not.

Input Format

First line will contain T, number of test cases. Then the test cases follow. Each test case consists of a single line of input,
containing three integers X,Y, and A as mentioned in the statement.

Output Format

For each test case, output YES if Chef is eligible to give the exam, NO otherwise.

CODE:

T = int(input())

for tc in range(T):

(x, y, a) = map(int, input().split(' '))

if(a>=x and a<y):

print("YES")

else:

print("NO")

INPUT:

3
HAARISINFOTECH- LEVEL2 LAB-BOOK

21 34 30

25 31 31

22 29 25

20 40 15

28 29 28

OUTPUT:

YES

NO

YES

NO

YES

PROBLEM-5:

Somu went to the gym today. He decided to do X sets of squats. Each set consists of 15 squats. Determine the total
number of squats that he did today.

Input Format

The first line contains a single integer T — the number of test cases. Then the test cases follow.

The first and only line of each test case contains an integer X — the total number of sets of squats that Somu did.

Output Format

For each test case, output the total number of squats done by Somu.

CODE:

T = int(input())

for i in range(T):

x = int(input())

4
HAARISINFOTECH- LEVEL2 LAB-BOOK

print(x*15)

INPUT:

99

OUTPUT:

15

60

1485

PROGRAM-6

Everyone who earns strictly more than Y rupees per year, has to pay a tax to Chef. Chef has allowed a special scheme
where you can invest any amount of money and claim exemption for it.

Input Format

The first line of input will contain a single integer T, denoting the number of test cases.

Each test case consists of a single line of input consisting of two space separated integers X and Y denoting the amount
you earned and the amount above which you will have to pay taxes.

Output Format

For each test case, output a single integer, denoting the minimum amount you need to invest.

CODE:

T = int(input())

for i in range(T):

(x, y) = map(int,input().split(' '))

print(x-y)

INPUT:

42

5
HAARISINFOTECH- LEVEL2 LAB-BOOK

87

51

21

OUTPUT:

PROGRAM-7

Chef visited his doctor. The doctor advised Chef to drink at least 2000 ml of water each day.

Chef drank X ml of water today. Determine if Chef followed the doctor's advice or not.

Input Format

The first line contains a single integer T — the number of test cases. Then the test cases follow. The first and only line of
each test case contains one integer X — the amount of water Chef drank today.

Output Format

For each test case, output YES if Chef followed the doctor's advice of drinking at least 2000 ml of water. Otherwise,
output NO.

CODE:

t = int(input())

for i in range(t):

x = int(input())

if x >= 2000:

print("YES")

else:

print("NO")

INPUT:

6
HAARISINFOTECH- LEVEL2 LAB-BOOK

2999

1450

2000

OUTPUT:

YES

NO

YES

PROGRAM-8

Biryani is the most ordered food. Chef wants to learn how to make world-class Biryani from a MasterChef. Chef will be
required to attend the MasterChef's classes for X weeks, and the cost of classes per week is Y coins. What is the total
amount of money that Chef will have to pay?

Input Format

The first line of input will contain an integer T — the number of test cases. The description of T test cases follows. The
first and only line of each test case contains two space-separated integers X and Y, as described in the problem
statement.

Output Format

For each test case, output on a new line the total amount of money that Chef will have to pay.

CODE:

t = int(input())

for i in range(t):

(x, y) = map(int, input().split(' '))

print(x*y)

INPUT:

1 10

1 15

2 10
7
HAARISINFOTECH- LEVEL2 LAB-BOOK

2 15

OUTPUT:

10

15

20

30

PROGRAM-9

Chef wants to become fit for which he decided to walk to the office and return home by walking. It is known that Chef's
office is X km away from his home.

If his office is open on 5 days in a week, find the number of kilometers Chef travels through office trips in a week.

Input Format

First line will contain T, number of test cases. Then the test cases follow. Each test case contains of a single line
consisting of single integer X.

Output Format

For each test case, output the number of kilometers Chef travels through office trips in a week.

CODE:

T = int(input())

for i in range(T):

a = int(input())

print(a*10)

INPUT:

10

OUTPUT:

8
HAARISINFOTECH- LEVEL2 LAB-BOOK

10

30

70

100

PROGRAM-10

According to the rules of Ludo, a player can enter a new token into the play only when he rolls a 6 on the die.

In the current turn, Chef rolled the number X on the die. Determine if Chef can enter a new token into the play in the
current turn or not.

Input Format

The first line contains a single integer T — the number of test cases. Then the test cases follow.

The first and only line of each test case contains one integer X — the number rolled by the Chef on the die.

Output Format

For each test case, output YES if the Chef can enter a new token in the game. Otherwise, output NO.

CODE:

T = int(input())

for i in range(T):

X = int(input())

if X ==6:

print("YES")

else:

print("NO")

INPUT:

9
HAARISINFOTECH- LEVEL2 LAB-BOOK

OUTPUT:

NO

YES

NO

PROGRAM-11

Chef is fond of burgers and decided to make as many burgers as possible.

Chef has A patties and B buns. To make 1 burger, Chef needs 1 patty and 1 bun.Find the maximum number of burgers
that Chef can make.

Input Format

The first line of input will contain an integer T — the number of test cases. The description of T test cases follows.

The first and only line of each test case contains two space-separated integers A and B, the number of patties and buns
respectively.

Output Format

For each test case, output the maximum number of burgers that Chef can make.

CODE:

t = int(input())

for i in range(t):

(x, y) = map(int, input().split(' '))

if(x>y or x==y):

print(y)

elif(y>x):

print(x)

INPUT:

22

23

32

10
HAARISINFOTECH- LEVEL2 LAB-BOOK

23 17

OUTPUT:

17

PROGRAM-11

Chef appeared for a placement test.

There is a problem worth X points. Chef finds out that the problem has exactly 10 test cases. It is known that each test
case is worth the same number of points.

Chef passes N test cases among them. Determine the score Chef will get.

Input Format

First line will contain T, number of test cases. Then the test cases follow.

Each test case contains of a single line of input, two integers X and N, the total points for the problem and the number of
test cases which pass for Chef's solution.

Output Format

For each test case, output the points scored by Chef.

CODE:

t = int(input())

for i in range(t):

(x, y) = map(int, input().split(' '))

x = x/10

print(int(x*y))

INPUT:

10 3

100 10

11
HAARISINFOTECH- LEVEL2 LAB-BOOK

130 4

70 0

OUTPUT:

100

52

PROGRAM-12

In Chefland, a tax of rupees 10 is deducted if the total income is strictly greater than rupees 100. Given that total income
is X rupees, find out how much money you get.

Input Format

The first line of input will contain a single integer T, denoting the number of test cases. The first and only line of each
test case contains a single integer X — your total income.

Output Format

For each test case, output on a new line, the amount of money you get.

CODE:

t = int(input())

for i in range(t):

a = int(input())

if(a>100):

print(a-10)

else:

print(a)

INPUT:

105

12
HAARISINFOTECH- LEVEL2 LAB-BOOK

101

100

OUTPUT:

95

91

100

PROGRAM-13

Chef has recently moved into an apartment. It takes 30 minutes for Chef to reach office from the apartment.

Chef left for the office X minutes before Chef was supposed to reach. Determine whether or not Chef will be able to
reach on time.

Input Format

The first line of input will contain a single integer T, denoting the number of test cases.Each test case consists of a single
integer X.

Output Format

For each test case, output YES if Chef will reach on time, NO otherwise.

CODE:

t = int(input())

for i in range(t):

x = int(input())

if(x>=30):

print("YES")

else:

print("NO")

INPUT:

30

13
HAARISINFOTECH- LEVEL2 LAB-BOOK

60

14

29

31

42

OUTPUT:

YES

YES

NO

NO

YES

YES

PROGRAM-14

Alice and Bob were having an argument about which of them is taller than the other. Charlie measured the heights of
Alice and Bob, and got to know that Alice's height is X centimeters and Bob's height is Y centimeters. Help Charlie decide
who is taller. It is guaranteed that X≠Y

Input Format

The first line of input will contain an integer T — the number of test cases. The description of T test cases follows.

The first and only line of each test case contains two integers X and Y, as described in the problem statement.

Output Format

For each test case, output on a new line A if Alice is taller than Bob, else output B. The output is case insensitive, i.e,
both A and a will be accepted as correct answers when Alice is taller.

CODE:

t = int(input())

for i in range(t):

(x, y) = map(int, input().split(' '))

if(x>y):

14
HAARISINFOTECH- LEVEL2 LAB-BOOK

print("A")

else:

print("B")

INPUT:

150 160

160 150

OUTPUT:

PROGRAM-15

Apple considers any iPhone with a battery health of 80% or above, to be in optimal condition. Given that your iPhone
has X% battery health, find whether it is in optimal condition.

Input Format

The first line of input will contain a single integer T, denoting the number of test cases.The first and only line of each test
case contains an integer X — the battery health.

Output Format

For each test case, output on a new line, YES, if the battery is in optimal condition, and NO otherwise.

CODE:

T = int(input())

for i in range(T):

x = int(input())

if(x>=80):

print("YES")

else:

print("NO")

INPUT:

15
HAARISINFOTECH- LEVEL2 LAB-BOOK

97

42

80

10

OUTPUT:

YES

NO

YES

NO

PROGRAM-16

In the current semester, you have taken X RTP courses, Y Audit courses and Z Non-RTP courses.

The credit distribution for the courses are:

4 credits for clearing each RTP course.

2 credits for clearing each Audit course.

No credits for clearing a Non-RTP course.

Assuming that you cleared all your courses, report the number of credits you obtain this semester.

Input Format

The first line contains a single integer T, the number of test cases. T test cases follow. Each test case consists of one line,
containing 3 integers separated by spaces.

The first integer is X, the number of RTP courses. The second integer is Y, the number of Audit courses. The third integer
is Z, the number of non-RTP courses.

Output Format

The output must consist of T lines.

CODE:

T = int(input())

for i in range(T):

16
HAARISINFOTECH- LEVEL2 LAB-BOOK

sum = 0

(x, y, z) = map(int,input().split(' '))

sum = x*4

sum += y*2

print(sum)

INPUT:

665

872

938

924

OUTPUT:

36

46

42

40

PROGRAM-17

Given the list of numbers, you are to sort them in non decreasing order.

Input

t – the number of numbers in list, then t lines follow [t <= 10^6].

Each line contains one integer: N [0 <= N <= 10^6]

Output

Output given numbers in non decreasing order

CODE:

lis=[]

t=int(input())

17
HAARISINFOTECH- LEVEL2 LAB-BOOK

while t>0:

n=int(input())

lis.append(n)

t-=1

lis.sort()

for i in range(0,len(lis)):

print(lis[i])

INPUT:

OUTPUT:

PROGRAM-18

Chef is playing a videogame, and is getting close to the end. He decides to finish the rest of the game in a single session.

There are X levels remaining in the game, and each level takes Chef Y minutes to complete. To protect against eye strain,
Chef also decides that every time he completes 3 levels, he will take a Z minute break from playing. Note that there is no
need to take this break if the game has been completed.

How much time (in minutes) will it take Chef to complete the game?

Input Format

18
HAARISINFOTECH- LEVEL2 LAB-BOOK

The first line of input will contain a single integer T, denoting the number of test cases.The first and only line of input will
contain three space-separated integers X, Y, and Z.

Output Format

For each test case, output on a new line the answer — the length of Chef's gaming session.

CODE:

T = int(input())

for i in range(T):

TimeTaken = 0

a=0

(x,y,z) = map(int, input().split())

for j in range(x):

TimeTaken = TimeTaken + y

if(j>0 and j%3==0):

TimeTaken = TimeTaken + z

print(TimeTaken)

INPUT:

2 12 10

3 12 10

7 20 8

24 45 15

OUTPUT:

24

36

156
19
HAARISINFOTECH- LEVEL2 LAB-BOOK

1185

PROGRAM-19

Chef received N candies on his birthday. He wants to put these candies in some bags. A bag has K pockets and each
pocket can hold at most M candies. Find the minimum number of bags Chef needs so that he can put every candy into a
bag.

Input Format

The first line of input will contain a single integer T, denoting the number of test cases. Each test case consists of a single
line containing three space-separated integers N,K,M.

Output Format

For each test case, print the minimum number of bags Chef needs so that he can put all the candies in one of the bags.

CODE:

T = int(input())

for i in range(T):

(n, k, m) = map(int, input().split())

if(n%m == 0):

a = (n/m)/k

b = round(a)

if(a>b):

b = b+1

print(b)

else:

print(b)

else:

a = (n/m)/k

b = round(a)

if(a>b):

b = b+1

20
HAARISINFOTECH- LEVEL2 LAB-BOOK

print(b)

else:

print(b)

INPUT:

623

312

841

25 4 2

OUTPUT:

PROGRAM-20

The Chessboard Distance for any two points (X1,Y1) and (X2,Y2) on a Cartesian plane is defined as max(∣X1
−X2∣,∣Y1−Y2∣).You are given two points(X1,Y1) and (X2,Y2). Output their Chessboard Distance.

Input Format

First line will contain T, the number of test cases. Then the test cases follow. Each test case consists of a single line of
input containing 4 space separated by space.

Output Format

For each test case, output in a single line the chessboard distance between (X1 ,Y1) and (X 2,Y 2 )

CODE:

T=int(input())

for i in range(T):

(x1,y1,x2,y2) = map(int,input().split(' '))


21
HAARISINFOTECH- LEVEL2 LAB-BOOK

a=abs(x1-x2)

b=abs(y1-y2)

if(a>b):

print(a)

else:

print(b)

INPUT:

2451

5553

1433

OUTPUT:

PROGRAM-21

Valentine's Day is approaching and thus Chef wants to buy some chocolates for someone special.

Chef has a total of X rupees and one chocolate costs Y rupees. What is the maximum number of chocolates Chef can
buy?

Input Format

First line will contain T, the number of test cases. Then the test cases follow. Each test case contains a single line of
input, two integers X,Y - the amount Chef has and the cost of one chocolate respectively.

Output Format

For each test case, output the maximum number of chocolates Chef can buy

CODE:

T=int(input())

for i in range(T):

22
HAARISINFOTECH- LEVEL2 LAB-BOOK

(x,y) = map(int,input().split(' '))

a = (x//y)

print(a)

INPUT:

5 10

16 5

35 7

100 1

OUTPUT:

100

PROGRAM-22

Consider a currency system in which there are notes of six denominations, namely, Rs. 1, Rs. 2, Rs. 5, Rs. 10, Rs. 50, Rs.
100.

If the sum of Rs. N is input, write a program to computer smallest number of notes that will combine to give Rs. N.

Input

The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.

Output

For each test case, display the smallest number of notes that will combine to give N, in a new line.

CODE:

T = int(input())

a = [100, 50, 10, 5, 2, 1]

for i in range(T):

23
HAARISINFOTECH- LEVEL2 LAB-BOOK

n = int(input())

b=1

for x in a:

if (x <= n):

b = b + (n // x )

n=n%x

print(b-1)

INPUT:

1200

500

242
OUTPUT:

12

PROGRAM-23

Tomya is a girl. She loves Chef Ciel very much.

Tomya like a positive integer p, and now she wants to get a receipt of Ciel's restaurant whose total price is exactly p.
Note that the i-th menu has the price 2^i-1 (1 ≤ i ≤ 12).

So please find the minimum number of menus whose total price is exactly p. Note that if she orders the same menu
twice, then it is considered as two menus are ordered.

Input

The first line contains an integer T, the number of test cases. Then T test cases follow. Each test case contains an integer
p.

Output
24
HAARISINFOTECH- LEVEL2 LAB-BOOK

For each test case, print the minimum number of menus whose total price is exactly p.

CODE:

t=int(input())

menu=[2048,1024,512,256,128,64,32,16,8,4,2,1]

for i in range(t):

p = int(input())

n=0

ans=0

while n < 12:

ans += p//menu[n]

p = p%menu[n]

if p==0:

break

n += 1

print(ans)

INPUT:

10

256

255

4096

OUTPUT:

25
HAARISINFOTECH- LEVEL2 LAB-BOOK

PROGRAM-24

You are given an array A=[A1,A2,…,AN] of length N. You can right rotate it any number of times (possibly, zero). What is
the maximum value of

Note: Right rotating the array [A1,A2,…,AN ] once gives the array [AN,A1,A2,…,AN−1]. For example, right rotating [1,2,3]
once gives [3,1,2], and right rotating it again gives [2,3,1].

Input Format

The first line of input will contain a single integer T, denoting the number of test cases. The description of the test cases
follows.

The first line of each test case contains a single integer N, denoting the length of array A.

The second line of each test case contains N space-separated integers A1,A2,…,AN— denoting the array A.

Output Format

For each test case, output on a new line the maximum value of A1 +AN you can get after several right rotations.

CODE:

T = int(input())

for i in range(T):

max_num = 0

size = int(input())

lst = list(map(int,input().split()))

i = len(lst)-1

loc = lst[0]+lst[i]

for x in range(i):

num = lst[i]+lst[i-1]

if(num>max_num):

max_num = num

i-=1

if(max_num<loc):

max_num=loc

26
HAARISINFOTECH- LEVEL2 LAB-BOOK

print(max_num)

INPUT:

58

5 10 15

4444

OUTPUT:

13

25

PROGRAM – 25

Chef has a unusual way of forming a triangle using gold coins, which is described as follows:

He puts 1 coin in the 1st row.

then puts 2 coins in the 2nd row.

then puts 3 coins in the 3rd row.

Input

The first line of input contains a single integer T denoting the number of test cases.

The first and the only line of each test case contains an integer N denoting the number of gold coins Chef has.

Output

For each test case, output a single line containing an integer corresponding to the maximum possible height of the
triangle that Chef can get.

CODE:

27
HAARISINFOTECH- LEVEL2 LAB-BOOK

def func(tot):

loc = 0

height = 0

while tot!=0 and tot>0:

if loc==0 and height == 0:

loc+=1

height+=1

tot-=loc

else:

i = loc+1

if(tot-i < 0):

break

else:

loc+=1

tot-=loc

height+=1

return height

T = int(input())

for i in range(T):

n = int(input())

print(func(n))

INPUT:

28
HAARISINFOTECH- LEVEL2 LAB-BOOK

OUTPUT:

PROGRAM – 26

Chef has an empty N×N chessboard. He places a Queen at (X,Y) and wonders - What are the number of cells that are
under attack by the Queen?

Input Format

The first line contains a single integer T - the number of test cases. Then the test cases follow.

The first and only line of each test case contains three integers N, X and Y, as described in the problem statement.

Output Format

For each test case, output in a single line, the total number of cells that are under attack by the Queen.

CODE:

def TRytD(size,xaxis,yaxis):

n=0

if(yaxis!=size and xaxis != 1):

while xaxis!=1 and yaxis!=size:

xaxis-=1

yaxis+=size

n+=1

else:

return 0

return n

29
HAARISINFOTECH- LEVEL2 LAB-BOOK

def TlftD(size,xaxis,yaxis):

n=0

if(yaxis != 1 and xaxis != 1):

while xaxis!=1 and yaxis!=1:

xaxis-=1

yaxis-=1

n+=1

else:

return 0

return n

def DRytD(size,xaxis,yaxis):

n=0

if(xaxis!=size and yaxis!=size):

while xaxis!=size and yaxis!=size:

xaxis+=1

yaxis+=1

n+=1

else:

return 0

return n

def DlftD(size,xaxis,yaxis):

n=0

if(xaxis!=size and yaxis!=1):

while xaxis!=size and yaxis!=1:

30
HAARISINFOTECH- LEVEL2 LAB-BOOK

xaxis+=1

yaxis-=1

n+=1

else:

return 0

return n

T = int(input())

for i in range(T):

(n, x, y) = map(int,input().split())

Qatck = 0

Qatck = (2*n)-2

Qatck += TRytD(n,x,y)

Qatck += TlftD(n,x,y)

Qatck += DRytD(n,x,y)

Qatck += DlftD(n,x,y)

print(Qatck)

INPUT:

111

322

321

222

150 62 41

OUTPUT:

31
HAARISINFOTECH- LEVEL2 LAB-BOOK

527

UNIT-V (LabBook)

PROBLEM-1

Python program to demonstrate encapsulation.

CODE:

class BankAccount:

def __init__(self, account_number, balance):

self.__account_number = account_number # private variable

self.__balance = balance # private variable

def deposit(self, amount):

self.__balance += amount

def withdraw(self, amount):

if amount <= self.__balance:

self.__balance -= amount

else:

print("Insufficient balance")

def get_balance(self):

return self.__balance

def get_account_number(self):
32
HAARISINFOTECH- LEVEL2 LAB-BOOK

return self.__account_number

account = BankAccount("123456789", 5000)

# access private variables using public methods

print(account.get_balance())

account.deposit(2000)

print(account.get_balance())

account.withdraw(3000)

print(account.get_balance())

OUTPUT:

5000

7000

4000

NOTE:

In this program, we have added a new public method get_account_number to the BankAccount class which
simply returns the private variable __account_number. This allows external code to access the private variable
in a controlled and safe way, without directly exposing the private variable.

PROGRAM-2

Python program to demonstrate inheritance

CODE:

class Animal:

def __init__(self, name, age):

self.name = name

self.age = age

33
HAARISINFOTECH- LEVEL2 LAB-BOOK

def make_sound(self):

print("The animal makes a sound")

#creating a class Dog inheriting class Animal

class Dog(Animal):

def __init__(self, name, age, breed):

super().__init__(name, age)

self.breed = breed

def make_sound(self):

print("Woof!")

#creating a class Cat inheriting class Animal

class Cat(Animal):

def __init__(self, name, age, color):

super().__init__(name, age)

self.color = color

def make_sound(self):

print("Meow!")

# create a Dog object

my_dog = Dog("Buddy", 3, "Golden Retriever")

print("the Dog object values ")

print(my_dog.name)
34
HAARISINFOTECH- LEVEL2 LAB-BOOK

print(my_dog.breed)

my_dog.make_sound()

# create a Cat object

my_cat = Cat("Fluffy", 2, "Grey")

print("the Cat object values ")

print(my_cat.name)

print(my_cat.color)

my_cat.make_sound()

OUTPUT:

the Dog object values

Buddy

Golden Retriever

Woof!

the Cat object values

Fluffy

Grey

Meow!

NOTE:

Using common functionalities of the super classes in the parent class is the best way to create hierarchies.

PROGRAM-3

Write a program to demonstrate public and private variables in a class

CODE

class Example:
35
HAARISINFOTECH- LEVEL2 LAB-BOOK

def __init__(self, public_var, private_var):

self.public_var = public_var # public variable

self.__private_var = private_var # private variable

def get_private_var(self):

return self.__private_var

def set_private_var(self, new_value):

self.__private_var = new_value

obj = Example("public", "private") #create an object

print(obj.public_var) # access public variable directly; outputs "public"

print(obj.get_private_var()) # access private variable using public method; outputs "private"

obj.set_private_var("new private") # modify private variable using public method

print(obj.get_private_var()) # outputs "new private"

OUTPUT:

public

private

new private

PRGRAM-4

Write a program to demonstrate classes and objects using python


36
HAARISINFOTECH- LEVEL2 LAB-BOOK

CODE:

class Car:

# initialize the class with a constructor

def __init__(self, make, model, year):

self.make = make

self.model = model

self.year = year

self.odometer_reading = 0

# define a method to get the car's description

def get_description(self):

long_name = f"{self.year} {self.make} {self.model}"

return long_name.title()

# define a method to read the car's odometer

def read_odometer(self):

print(f"This car has {self.odometer_reading} miles on it.")

# define a method to update the odometer reading

def update_odometer(self, mileage):

if mileage >= self.odometer_reading:

self.odometer_reading = mileage

else:

print("You can't roll back an odometer!")

37
HAARISINFOTECH- LEVEL2 LAB-BOOK

# create an instance of the class called "my_car"

my_car = Car("audi", "a4", 2019)

# access the attributes of the instance

print(my_car.make)

print(my_car.model)

print(my_car.year)

# call the instance's methods

print(my_car.get_description())

my_car.read_odometer()

my_car.update_odometer(1500)

my_car.read_odometer()

OUTPUT:

audi

a4

2019

2019 Audi A4

This car has 0 miles on it.

This car has 1500 miles on it.

PROGRAM-5

Write a program to demonstrate abstraction using python

CODE:
38
HAARISINFOTECH- LEVEL2 LAB-BOOK

from abc import ABC, abstractmethod

# Define an abstract base class called "Vehicle"

class Vehicle(ABC):

# Define an abstract method called "start_engine"

@abstractmethod

def start_engine(self):

pass

# Define a class called "Car" that inherits from "Vehicle"

class Car(Vehicle):

def start_engine(self):

print("Starting car engine")

# Define a class called "Motorcycle" that inherits from "Vehicle"

class Motorcycle(Vehicle):

def start_engine(self):

print("Starting motorcycle engine")

my_car = Car()

my_motorcycle = Motorcycle()

my_car.start_engine()

my_motorcycle.start_engine()

OUTPUT:

Starting car engine


39
HAARISINFOTECH- LEVEL2 LAB-BOOK

Starting motorcycle engine

PROGRAM-6

Write a program to demonstrate a simple e-commerce system, where customer can place orders.

CODE:

class Customer:

def __init__(self, name, email):

self.name = name

self.email = email

self.orders = []

def add_order(self, order):

self.orders.append(order)

def get_total_spent(self):

return sum(order.get_total_price() for order in self.orders)

class Order:

def __init__(self, order_number):

self.order_number = order_number

self.items = []

def add_item(self, item, quantity):

self.items.append((item, quantity))

def get_total_price(self):
40
HAARISINFOTECH- LEVEL2 LAB-BOOK

return sum(item.get_price() * quantity for item, quantity in self.items)

class Item:

def __init__(self, name, price):

self.name = name

self.price = price

def get_price(self):

return self.price

# create some example customers, orders, and items

customer1 = Customer("Alice", "alice@example.com")

customer2 = Customer("Bob", "bob@example.com")

order1 = Order(1)

order1.add_item(Item("Apple", 0.99), 3)

order1.add_item(Item("Banana", 0.49), 2)

customer1.add_order(order1)

order2 = Order(2)

order2.add_item(Item("Orange", 1.49), 4)

customer2.add_order(order2)

# print out the total amount spent by each customer

print(f"{customer1.name} spent ${customer1.get_total_spent():.2f}")

print(f"{customer2.name} spent ${customer2.get_total_spent():.2f}")


41
HAARISINFOTECH- LEVEL2 LAB-BOOK

OUTPUT

Alice spent $3.95

Bob spent $5.96

PROGRAM-7

Write a program to demonstrate Polymorphism using python

CODE

class Shape:

def draw(self):

pass

class Circle(Shape):

def draw(self):

print("Drawing a circle")

class Square(Shape):

def draw(self):

print("Drawing a square")

class Triangle(Shape):

def draw(self):

print("Drawing a triangle")

# create a list of different shapes

shapes = [Circle(), Square(), Triangle()]

42
HAARISINFOTECH- LEVEL2 LAB-BOOK

# call the draw method on each shape

for shape in shapes:

shape.draw()

OUTPUT:

Drawing a circle

Drawing a square

Drawing a triangle

PROGRAM-8

Write a program to demonstrate multiple instances for a class

CODE:

class PartyAnimal:

x=0

name = ''

def __init__(self, nam):

self.name = nam

print(self.name,'constructed')

def party(self) :

self.x = self.x + 1

print(self.name,'party count',self.x)

s = PartyAnimal('Sally')

j = PartyAnimal('Jim')

s.party()

j.party()
43
HAARISINFOTECH- LEVEL2 LAB-BOOK

s.party()

OUTPUT:

Sally constructed

Jim constructed

Sally party count 1

Jim party count 1

Sally party count 2

PROGRAM-9

Write a program to the type of a class

CODE

class PartyAnimal:

x=0

def party(self) :

self.x = self.x + 1

print("So far",self.x)

an = PartyAnimal()

print ("Type", type(an))

print ("Type", type(an.x))

print ("Type", type(an.party))

OUTPUT:

Type <class '__main__.PartyAnimal'>

Type <class 'int'>

Type <class 'method'>


44
HAARISINFOTECH- LEVEL2 LAB-BOOK

PROGRAM-10

Write a program to visualize the lifecycle of an object

CODE:

class PartyAnimal:

x=0

def __init__(self):

print('I am constructed')

def party(self) :

self.x = self.x + 1

print('So far',self.x)

def __del__(self):

print('I am destructed', self.x)

an = PartyAnimal()

an.party()

an.party()

an = 42

print('an contains',an)

OUTPUT:

I am constructed

So far 1

So far 2

I am destructed 2
45
HAARISINFOTECH- LEVEL2 LAB-BOOK

an contains 42

46

You might also like