0% found this document useful (0 votes)
10 views

Python.record

The document contains a detailed record of Python programming experiments conducted by a student, including various topics such as data types, functions, and algorithms. Each experiment includes a program statement, algorithm, program code, output, and result, demonstrating the successful implementation of Python concepts. The experiments are dated and organized sequentially, showcasing the student's learning progress in Python programming.

Uploaded by

manojisk291
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python.record

The document contains a detailed record of Python programming experiments conducted by a student, including various topics such as data types, functions, and algorithms. Each experiment includes a program statement, algorithm, program code, output, and result, demonstrating the successful implementation of Python concepts. The experiments are dated and organized sequentially, showcasing the student's learning progress in Python programming.

Uploaded by

manojisk291
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

REG.

NO:212224230234

S.N DATE LIST OF EXPERIMENTS. PAG MARK SIG


O E.N S N
O
28.09. PYTHON BASICS 3
1(A) 24
03.10. DATATYPES 5
1(B) 24
05.10. VARIABLES & EXPRESSIONS OPERATOR 7
1(C) 24
10.10. CONDITIONAL STATEMENTS 9
1(D) 24
17.10. ITERATIVE STATEMENTS 11
2(A) 24
19.10. FUNCTIONS 13
2(B) 24
24.10. BUILT-IN FUNCTIONS & LAMBDA 15
2(C) 24 FUNCTIONS
26.10. LOOPING(PATTERNS) 17
2(D) 24
07.11. STRING 19
3(A) 24
14.11. REGEX 21
3(B) 24
15.11. LISTS 23
3(C) 24
16.11. TUPLES 25
3(D) 24
21.11. DICTIONARY 27
4(A) 24
22.11. EXCEPTION 29
4(B) 24
23.11. FILES MODULES 31
4(C) 24
28.11. CLASSES & OBJECTS 33

1
REG.NO:212224230234

4(D) 24
29.11. NUMPY - I 35
5(A) 24
05.12. NUMPY - II 37
5(B) 24
06.12. PANDAS - I 39
5(C) 24
07.12. PANDAS - II 41
5(D) 24
12.12. POLYMORPHISM 43
6(A) 24
13.12. OPERATOR OVERLOADING 45
6(B) 24
14.12. ABSTRACTION 47
6(C) 24
6(D) 19.12. ENCAPSULATION 49
24

2
REG.NO:212224230234

EX.NO:1(A) PYTHON BASICS


DATE: 28.09.24

PROGRAM STATEMENT:

Write a python program to get and print any vowels using character literal.​

For example:​

Input​ Result​
A A​
O O

ALGORITHM:

1. Accept the Input for a using input()

2: Accept Input for b using input()

3: Print the Value of a using print()

3
REG.NO:212224230234

4: Print the Value of b using print()

PROGRAM:

a=input()​
b=input()​
print(a)​
print(b)

OUTPUT:

4
REG.NO:212224230234

RESULT:

Thus the python program to get and print any vowels using character literal is created
successfully.

EX.NO:1(B) DATATYPES
DATE: 03.10.24

PROGRAM STATEMENT:

Write a python program to read two numbers and convert and print them into a complex
number and print the real and imaginary part of the complex number.​

For example:​

Input​ Result​
5 (5+6j)​
6 5.0
6.0

5
REG.NO:212224230234

ALGORITHM:
1. Get the input for value a using input()
2. Get the input for value b using input()
3. Use complex() function to create a complex number x
4. Print the complex number x
5. Print real part of the complex number using x.real
6. Print the imaginary part of the complex number using x.imag

PROGRAM:

a=int(input())​
b=int(input())​
x=complex(a,b)​
print(x)​
print(x.real)​
print(x.imag)

OUTPUT:

6
REG.NO:212224230234

RESULT:

Thus the python program to read two numbers and convert and print them into a complex
number and print the real and imaginary part of the complex number is created
successfully.

EX.NO:1(C) VARIABLES & EXPRESSIONS


OPERATOR
DATE: 05.10.24

PROGRAM STATEMENT:

Write a python program to check the identity of the given two values using "is not"
operator.​

For example:​

7
REG.NO:212224230234

Input​ Result​
10 ​
20 a and b do not have same identity

ALGORITHM:

1. Get the input for the two integers using input()


2. The program uses is not operator and compares if a and b do not have same identity
3. If the condition is true ,the program prints that a and b do not have same identity
4. If the condition is false , the program prints a and b have same identity

PROGRAM:

a=int(input())​
b=int(input())​
if(a is not b):​
print("a and b do not have same identity")​
else:​
print("a and b have same identity")

OUTPUT:

8
REG.NO:212224230234

RESULT:

Thus the python program to check the identity of the given two values using is not operator
is created successfully.

EX.NO:1(D) CONDITIONAL STATEMENTS

9
REG.NO:212224230234

DATE: 10.10.24

PROGRAM STATEMENT:

write a python program to find the minimum of two integer numbers using conditional
Expression(Ternary)​
For example:​

Input Result​
5 The minimum of 5 and 3 is 3​
3

-15 The minimum of -15 and -20 is -20


-20

ALGORITHM:

1. Get the input for two integers a and b using input()


2. using if else statement , it compares if a is greater than b
3. If the condition is true, it prints The minimum is b
4. If the condition is false, it prints The minimum is a

PROGRAM:

a=int(input())​
b=int(input())​
if (a>b):​
print("The minimum of",a,"and",b,"is" ,b)​
else:​
print("The minimum of",a,"and",b,"is",a)

10
REG.NO:212224230234

OUTPUT:

RESULT:

Thus the python program to find the minimum of two integer numbers using conditional
expression (Ternary) is created successfully.

EX.NO:2(A) ITERATIVE STATEMENTS

11
REG.NO:212224230234

DATE:17.10.24

PROGRAM STATEMENT:

Python Program to find the sum of series 1^1+2^2+3^3... +N^N.​

For example:​

Input​ Result​
3 The sum of the series = 32

ALGORITHM:

1. Read the integer n from the user .


2. Set the variable s to 0.
3.For i from 1 to n (inclusive):
●​ Compute the term i^i
●​ Add the computed term to s .
4. After completing the iteration, print the value of S.

PROGRAM:

n=int(input())​
s=0​
for i in range(1,n+1):​
s+=i**i​
print("The sum of the series = ",s)

12
REG.NO:212224230234

OUTPUT:

RESULT:

Thus the python program to find the sum of series 1^1 + 2^2 + 3^3 +........+N^N is created
successfully.

EX.NO:2(B) FUNCTIONS

13
REG.NO:212224230234

DATE:19.10.24

PROGRAM STATEMENT:

write a python program to define a function that accepts length ,width of a rectangle and
returns the area of a rectangle.​
For example:​

Test​ Input​ Result​


print(area(l,b)) 12 372​
31

ALGORITHM:

1.​Input the length l from the user.


2.​Input the breadth b from the user.
3.​Define a function area(l, b):
4.​Inside the function, calculate the area as area = l * b
5.​Return the value of area.
6.​Call the area(l, b) function with the values of l and b.
7.​Print the result of the area calculation.
8.​End the program.

PROGRAM:​

l=int(input())​
b=int(input())​
def area(l,b):​
area=l*b​
return area

14
REG.NO:212224230234

OUTPUT:

RESULT:

Thus the python program to define a function that accepts length, width of a rectangle and
return the area of a rectangle is created successfully.

EX.NO:2(C) BUILT-IN FUNCTIONS & LAMBDA


FUNCTIONS
DATE:24.10.24

PROGRAM STATEMENT:

15
REG.NO:212224230234

Write a lambda function which takes z as a parameter and returns z*11 using python​

For example:​

Input​ Result​
18 198​

ALGORITHM:

1. Get the input of a number z using input()


2. Define the lambda function multiplt_by_11, which performs the multiplication z * 11.
3. Call the lambda function multiply_by_11(z) with the input value of z.
4. Output the result of the multiplication.
5. End the program

PROGRAM:

multiply_by_11 = lambda z: z * 11​

z = int(input())​
print(multiply_by_11(z))

OUTPUT:

16
REG.NO:212224230234

RESULT:

Thus the python program to write a lambda function which takes z as a parameter and
returns z*11 is created successfully.

EX.NO:2(D) LOOPING (PATTERNS)


DATE:26.10.24

17
REG.NO:212224230234

PROGRAM STATEMENT:

Python Program to Print inverted pyramid pattern with the same digit.Get the input from
the user.​

For example:​

Input​ Result​
6 666666
66666​
6666​
666​
66​
6

ALGORITHM:

1.​Input the number of rows from the user.


2.​Set num equal to rows.
3.​Start a loop that runs from rows to 1. For each iteration, the variable i represents the
current row number.
4.​Inside the outer loop, start another loop that runs i times. In each iteration, print the
value of num without moving to the next line.
5.​After printing all num values for the current row, print a newline (print()).
6.​End the program.

PROGRAM:

rows=int(input())​
num = rows​
for i in range(rows, 0, -1):​
for j in range(0, i):​
print(num, end=" ")​
print()

18
REG.NO:212224230234

OUTPUT:

RESULT:
Thus the python program to print inverted pyramid pattern with the same digit is created
successfully.

19
REG.NO:212224230234

EX.NO:3(A) STRING
DATE:07.11.24

PROGRAM STATEMENT:

Write a python function that accepts the string and prints the reverse of that string.​

For example:​

Test​ Result​
slice("redraH eltsuH")​
The reversed string is 'Hustle Harder'

ALGORITHM:

1. Accept the input string from the user using the input() function.
2. The function slice(string) is defined to reverse the input string. Inside the function, a new
string new_string is created by slicing the original string with the slice notation [::-1], which
reverses the order of characters in the string.
3. The reversed string is printed in a formatted manner.
4. The function prints the reversed string using the print() function, along with a message
indicating the result.
5. The function execution is completed after printing the reversed string

20
REG.NO:212224230234

PROGRAM:

string=input()​
def slice(string):​
new_string = string[::-1]​
print(f"The reversed string is '{new_string}'")

OUTPUT:

RESULT:

Thus the python program to write a python function that accepts the string and prints the
reverse of that string is created successfully.

21
REG.NO:212224230234

EX.NO:3(B) REGEX
DATE:14.11.24

PROGRAM STATEMENT:

Write a Python program to find sequences of Lower case letters joined with a '@'.​

For example:​

Input​ Result​
saveetha@engineering Found a match!​
saveetha engineering Not matched!

ALGORITHM:
1. Accept the input string using the input() function.
2. Define a regular expression pattern r'[a-z]+@[a-z]+' in the function. This pattern is
designed to match a simple email-like structure.
3.[a-z]+: Matches one or more lowercase letters (a-z).
4.@: Matches the literal '@' symbol.
5.[a-z]+: Matches one or more lowercase letters (a-z) after the '@' symbol.
6. Use re.search(pattern, input_string) to search for the defined pattern in the input string.
This function will search for the first occurrence of the pattern in the string.
7. If a match is found (if match), the function prints "Found a match!".
8. If no match is found (else), the function prints "Not matched!".
9.The function execution finishes after printing the result.

22
REG.NO:212224230234

PROGRAM:

import re​
def find_sequence(input_string):​
pattern = r'[a-z]+@[a-z]+'​
match = re.search(pattern, input_string)​
if match:​
print("Found a match!")​
else:​
print("Not matched!")​

input_string = input()​
find_sequence(input_string)

OUTPUT:

RESULT:

Thus the python program to find sequences of lower case letters joined with a ‘@’ is
created successfully.

23
REG.NO:212224230234

EX.NO:3(C) LISTS
DATE:15.11.24

PROGRAM STATEMENT:

Write a python program to compute the average marks of best of two of three assignment
tests. maximum marks for each assignment is 25.fractional marks in final average are
rounded off to the nearest and highest whole number.​

assign_marks=[24,19,22]​

For example:​

Result​
[24, 19, 22]​
Highest 24 Second Highest 22​
Final Average Marks: 23

ALGORITHM:
1.​The list is predefined with three elements
2.​Print the original list using print(list).
3.​ Compute the average of the numbers in the list using sum(list) / len(list). The sum
of the elements in the list is divided by the number of elements in the list to get the
average.
4.​ Add 1 to the calculated average using the +1 operation.
5.​ Round the result to the nearest integer using the round() function and store the
result in the variable a.
6.​ The first value in the list (list[0]) is considered as the highest, and the third value
(list[2]) is considered as the second highest. These values are directly accessed by
their index positions.
7.​ Print the highest, second highest, and the final average (rounded) value using a
formatted string.

24
REG.NO:212224230234

PROGRAM:

list=[24, 19, 22]​


print(list)​
a=round(sum(list)/len(list)+1)​
print(f"Highest {list[0]} Second Highest {list[2]}\nFinal Average Marks: {a}")

OUTPUT:

RESULT:

25
REG.NO:212224230234

Thus the python program to compute the average marks of best of two of three
assignment tests. maximum marks for each assignment is 25.fractional marks in final
average are rounded off to the nearest and highest whole number is created successfully.

EX.NO:3(D) TUPLES
DATE:16.11.24

PROGRAM STATEMENT:

Write a python program to create the tuple by the multiples of 9 up to N and the print
length of the tuple. Get the N value from the user.​

For example:​

Input​ Result​
49 (9, 18, 27, 36, 45)​
Length of the tuple is 5

ALGORITHM:

1. Get the input using input()


2. Use a generator expression inside a tuple(), to create a tuple multiples_of_9
3. The generator iterates over a range from 9 to N. This generates all multiples of 9 less
than N
4. Print the generated tuple
5. use len() function to find the length of tuple multiples_of_9
6. Print the length of the tuple.

PROGRAM:

26
REG.NO:212224230234

N=int(input())​
multiples_of_9=tuple(i for i in range(9,N,9))​
print(multiples_of_9)​
print("Length of the tuple is", len(multiples_of_9))

OUTPUT:

RESULT:

27
REG.NO:212224230234

Thus the python program to create the tuple by the multiples of 9 up to N and the print
length of the tuple is created successfully.

EX.NO:4(A) DICTIONARY
DATE:21.11.24

PROGRAM STATEMENT:

Write a Python script to check whether a given key 5,9 already exists in a dictionary.​

d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}​

For example:​

Result​
Key is present in the dictionary ​
Key is not present in the dictionary

ALGORITHM:

1. A dictionary d with key value pairs is given


2. A list keys containing keys to be checked for presence in the dictionary, e.g., [5, 9]
3. Iterate through each key in the keys list using a for loop.
4. For each key, check if it exists in the dictionary d.
5. Use the in operator to check if the key is present in the dictionary d.

28
REG.NO:212224230234

6. If the key is found in the dictionary, it prints key is present in the dictionary
7. If the key is not found in the dictionary, it prints key is not present in the dictionary

PROGRAM:

d={1:10,2:20,3:30,4:40,5:50,6:60}​
keys=[5,9]​
for key in keys:​
if key in d:​
print("Key is present in the dictionary")​
else:​
print("Key is not present in the dictionary")

OUTPUT:

29
REG.NO:212224230234

RESULT:

Thus the python program to write a Python script to check whether a given key 5,9
already exists in a dictionary is created successfully.

EX.NO:4(B) EXCEPTION
DATE:22.11.24

PROGRAM STATEMENT:

Place result="You can't divide with 0" to the right place so that program avoids
ZeroDivisionError.​

For example:​

Input​ Result​
5​
0 You can't divide with 0

ALGORITHM:
1. Get the input a using input()
2. Get the input b using input()
3. In the try block:
●​ Calculate the result of a/b
●​ Print the result if no error occurs.
4. In the except block:

30
REG.NO:212224230234

●​ If an exception occurs (such as division by zero), it prints the message: "You can't
divide with 0".

PROGRAM:

a=int(input())​
b=int(input())​
try:​
result=a/b​
print(result)​
except:​
print("You can't divide with 0")

OUTPUT:

31
REG.NO:212224230234

RESULT:
Thus the python program to Place result="You can't divide with 0" to the right place so that
program avoids ZeroDivisionError is created successfully.​

EX.NO:4(C) FILES & MODULES


DATE:23.11.24

PROGRAM STATEMENT:

[Oracle]Calculate the average word length in a file:Write a function to calculate the


average word length in a file.​
For example:

32
REG.NO:212224230234

Test Input Result


file_path = 'test_case_1.txt'
file_content = input()
create_file(file_path, 5.333333333333
apple banana apple
file_content) 333
print(average_word_length(file_p
ath))
file_path = 'test_case_1.txt'
file_content = input()
create_file(file_path, This is the first
3.8
file_content) line.
print(average_word_length(file_p
ath))

ALGORITHM:

1.​create_file function:
●​ Takes file_path and content as inputs.
●​ Opens the file for writing, writes the content, and closes the file.
2.​average_word_length function:
●​ Takes file_path as input.
●​ Open the file for reading, read the content, and split it into words.
●​ Count the total length of all words.
●​ Compute and return the average word length.
3.​End the program.

PROGRAM:

def create_file(file_path, content):​


with open(file_path, 'w') as file:​

33
REG.NO:212224230234

file.write(content)​

def average_word_length(file_path):​
with open(file_path,'r') as file:​
d=file.read()​
x=d.split()​
c=0​
for a in x:​
c+=len(a)​
s=c/len(x)​
return s

OUTPUT:

RESULT:

Thus the python program to calculate the average word length in a file:Write a function to
calculate the average word length in a file is created successfully.

EX.NO:4(D) CLASSES & OBJECTS


DATE:28.11.24

34
REG.NO:212224230234

PROGRAM STATEMENT:

Write a python program to find perimeter of a circle using class name 'cse' and function
name 'mech'.​
For example:​

Input​ Result​
7 Perimeter of circle: 43.98​
10 Perimeter of circle: 62.83

ALGORITHM:
1. Get the input a using input()
2. Use the formula b=2×π×ab = 2 \times \pi \times ab=2×π×a to calculate the perimeter of
the circle, where π\piπ is approximated by math.pi
3. Round the result to two decimal places using round(b,2)
4. Print the result in the format: "Perimeter of circle: {rounded value}".

PROGRAM:

import math​
def mech(a):​
b=2*math.pi*a​
print(f"Perimeter of circle: {round(b,2)}")​
a=int(input())​
mech(a)

OUTPUT:

35
REG.NO:212224230234

RESULT:

Thus the python program to find perimeter of a circle using class name 'cse' and function
name 'mech' is created successfully.

EX.NO:5(A) NUMPY - I
DATE:29.11.24

36
REG.NO:212224230234

PROGRAM STATEMENT:

Create a numpy program to find the variance of the given numpy array.​

For example:​

Input​ Result​
[[15,26],[18,62]] 352.1875

ALGORITHM:

1. Get the input a using input(). The input should be in list format
2. Converts the input to a NumPy array using np.array(a)
3. Compute the variance of the NumPy array using np.var(arr), which measures how far
the numbers are from the mean of the array.
4. Print the result of the variance calculation.

PROGRAM:

import numpy as np​


a=eval(input())​
arr=np.array(a)​
v=np.var(arr)​
print(v)

37
REG.NO:212224230234

OUTPUT:

RESULT:

Thus the python program to create a numpy program to find the variance of the given
numpy array is created successfully.

38
REG.NO:212224230234

EX.NO:5(B) NUMPY - II
DATE:05.12.24

PROGRAM STATEMENT:

Create a numpy program to find the sum of first column in a given numpy array.​

For example:​

Input​ Result​
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] [[ 1 2 3]​
[ 4 5 6]​
[ 7 8 9]​
[10 11 12]]​
22

ALGORITHM:
1. Read a list or array-like input from the user, such as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
2. Convert the input into a NumPy array using np.array(a)
3. Reshape the array into a 4x3 matrix using arr.reshape(4,3)
4. Extract the first column using arr_reshaped[:,0] and compute the sum of its elements
using np.sum()
5. Print the reshaped 4x3 array.
6. Print the sum of the elements in the first column.

PROGRAM:

39
REG.NO:212224230234

import numpy as np​


arr=np.array(eval(input()))​
arr_reshaped = arr.reshape(4, 3)​
first_column_sum = np.sum(arr_reshaped[:, 0])​

print (arr_reshaped)​
print( first_column_sum)

OUTPUT:

RESULT:

40
REG.NO:212224230234

Thus the python program to create a numpy program to find the sum of first column in a
given numpy array is created successfully.

EX.NO:5(C) PANDAS - I
DATE:06.12.24

PROGRAM STATEMENT:

Write a Python Pandas program first to carry out the Multiplication mathematics operations
for the following two series a1 and a2.​

For example:​

Input​ Result​
[6, 6, 6, 6, 6]​
[1, 2, 5, 7, 9] Multiplication of two Series:​
0 6​
1 12​
2 30​
3 42​
4 54​
dtype: int64

ALGORITHM:
1. Get two inputs a and b
2. Convert the input data into Pandas Series
3. perform multiplication between two series
4. Print the result of the multiplication
5. Display the Series result

PROGRAM:

import pandas as pd​


a=eval(input())​

41
REG.NO:212224230234

b=eval(input())​
a1=pd.Series(a)​
a2=pd.Series(b)​
result=a1*a2​
print("Multiplication of two Series:")​
print(result)

OUTPUT:

42
REG.NO:212224230234

RESULT:
Thus the python program to write a Python Pandas program first to carry out the
Multiplication mathematics operations for the following two series a1 and a2 is created
successfully.

EX.NO:5(D) PANDAS - II
DATE:07.12.24

PROGRAM STATEMENT:
Create a Pandas program to merge two given datasets using multiple join keys.

ALGORITHM:
1. Accept two DataFrames as input
2. Print the original DataFrames a and b
3. Merge the DataFrames on common columns
4. Print the resulting merged DataFrame c

PROGRAM:

43
REG.NO:212224230234

import pandas as pd​


a=pd.DataFrame(eval(input()))​
b=pd.DataFrame(eval(input()))​
print("Original DataFrames:")​
print(a)​
print("--------------------")​
print(b)​
c=pd.merge(a,b)​
print()​
print("Merged Data:")​
print(c)

OUTPUT:

44
REG.NO:212224230234

RESULT:
Thus the pandas program to merge two given datasets using multiple join keys is created
successfully.

EX.NO:6(A) POLYMORPHISM
DATE:12.12.24

PROGRAM STATEMENT:

Create two classes Employee and Admin. These two different classes have the same
method name info(). This method contains information(name, department) about employee
in Employee class and admin in Admin class.after initializing classes, Create two objects
for respective classes. Then the method info() is called. Once by the object of Employee
class and once by the object of Admin class.​

ALGORITHM:

1. Define two classes (Employee and Admin) , each with an info() method that prints
specific information
2. Create objects of both classes (obj_emp for Employee and obj_adm for Admin)
3. Define the function func() that calls the info() method on both objects
4. Call func(), which invokes the info() methods and prints the respective information

PROGRAM:

45
REG.NO:212224230234

class Employee:​
def info(self):​
print("Rooney from Electronics")​
class Admin:​
def info(self):​
print("Kalesh from CS")​
obj_emp = Employee()​
obj_adm = Admin()​
def func():​
obj_emp.info()​
obj_adm.info()​
func()

OUTPUT:

RESULT:

Thus the python program to create two classes Employee and Admin. These two different
classes have the same method name info(). This method contains information(name,
department) about employee in Employee class and admin in Admin class.after initializing
classes, Create two objects for respective classes. Then the method info() is called. Once

46
REG.NO:212224230234

by the object of Employee class and once by the object of Admin class is created
successfully.

EX.NO:6(B) OPERATOR OVERLOADING


DATE:13.12.24

PROGRAM STATEMENT:

Write a Python program for simply using the overloading operator for adding two objects.

ALGORITHM:

1. Take input for the integers a and b using input()


2. Take input for the strings c and d
3. Print the sum of integers a and b
4. Print the concatenation of strings c and d

PROGRAM:

a=int(input())​
b=int(input())​
c=input()​

47
REG.NO:212224230234

d=input()​
print(f"adding integers :" ,a+b)​
print(f"adding strings :",c+d)

OUTPUT:

48
REG.NO:212224230234

RESULT:

Thus the Python program for simplifying using the overloading operator for adding two
objects is created successfully.

EX.NO:6(C) ABSTRACTION
DATE:14.12.24

PROGRAM STATEMENT:

Create an abstract base class has a concrete method sleep() that will be the same for all
the child classes. So, we do not define it as an abstract method, thus saving us from code
repetition. On the other hand, the sounds that animals make are all different. For that
purpose, define the sound() method as an abstract method. then implement it in all child
classes.

ALGORITHM:

1. Import required modules (ABC, abstractmethod)


2. Define Animal as an abstract class with an abstract method sound()
3. Define subclasses (Snake, Dog, Lion, Cat)
4. Create a cat object and call the sleep() method then call the sound() method
5. Create a Snake object and call the sound() method

PROGRAM:

from abc import ABC,abstractmethod​

49
REG.NO:212224230234

class Animal(ABC):​
@abstractmethod​
def sound(self):​
pass​

class Snake(Animal):​
def sound(self):​
print("I can hiss")​

class Dog(Animal):​
def sound(self):​
print("I can bark")​

class Lion(Animal):​
def sound(self):​
print("I can roar")​

class Cat(Animal):​
def sound(self):​
print("I can meow")​
def sleep(self):​
print("I am going to sleep in a while")​

c = Cat()​
c.sleep()​
c.sound()​
c = Snake()​
c.sound()

OUTPUT:

50
REG.NO:212224230234

RESULT:

Thus the python program to create an abstract base class has a concrete method sleep()
that will be the same for all the child classes. So, we do not define it as an abstract
method, thus saving us from code repetition. On the other hand, the sounds that animals
make are all different. For that purpose, define the sound() method as an abstract method.
then implement it in all child classes is created successfully.

EX.NO:6(D) ENCAPSULATION
DATE:19.12.24

PROGRAM STATEMENT:

Create Counter class which has one attribute called current which defaults to zero. And it
has three methods:​

increment() increases the value of the current attribute by one.​


value() returns the current value of the current attribute​
reset() sets the value of the current attribute to zero​
create a new instance of the Counter class and calls the increment() method three times
before showing the current value of the counter to the screen

ALGORITHM:

1. Create a Counter object (counter ) with the initial value current = 0


2. Increment counter.current by 1 three times
3. Retrieve and print the current value (counter.current) , which should be 3 after three
increments.

51
REG.NO:212224230234

PROGRAM:

class Counter:​
def _init_(self):​
self.current = 0​

def increment(self):​
self.current += 1​

def value(self):​
return self.current​

def reset(self):​
self.current = 0​

counter = Counter()​

counter.increment()​
counter.increment()​
counter.increment()​

print(counter.value())

OUTPUT:

52
REG.NO:212224230234

RESULT:
Thus the python program to create a new instance of the Counter class and calls the
increment() method three times before showing the current value of the counter to the
screen is created successfully.

53

You might also like