0% found this document useful (0 votes)
2 views24 pages

Python

This document outlines the Python Programming Laboratory course at Bharath Institute of Higher Education & Research, detailing various programming exercises and their objectives. Each exercise includes an aim, algorithm, program code, and expected results for tasks like swapping variables, calculating distances, finding grades, and manipulating lists. The document serves as a record for students' practical work in the course.
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)
2 views24 pages

Python

This document outlines the Python Programming Laboratory course at Bharath Institute of Higher Education & Research, detailing various programming exercises and their objectives. Each exercise includes an aim, algorithm, program code, and expected results for tasks like swapping variables, calculating distances, finding grades, and manipulating lists. The document serves as a record for students' practical work in the course.
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/ 24

173, Agaram Road, Selaiyur, Chennai-600073

BHARATH INSTITUTE OF HIGHER EDUCATION & RESEARCH

Department of Computer Science & Engineering

PYTHON PROGRAMMING LABORATORY

COURSE CODE: U20CSCJ03

Name :
Year :
Semester :
Section :
University Register No. :
173, Agaram Road, Selaiyur, Chennai-600073

Department of Computer Science & Engineering

COURSE CODE : U20CSCJ03

PYTHON PROGRAMMING LABORATORY

Name :

Year :

Semester :

Section :

University Register No. :

Certified that this is the bonafide record of work done by the above student in the PYTHON

PROGRAMMING LABORATORY (Sub Code: U20CSCJ03) during the month……………

Signature of Faculty-In-Charge Signature of Head of Department

Submitted for the practical Examination held on at Bharath Institute of Higher


Education & Research.

Signature of Internal Examiner Signature of External Examiner


INDEX

S.no Date of Name of the program Page Signature


completion no. of
Faculty
1a. Swap the values of two variables

1b. Calculate distance between two points

2. Find the grade of student using the marks scored


in all subjects
3a. Find the sum of series 1/12 +1/22 +…+1/N2

3b. Calculate GCD using recursive function

4. Program that accepts a string from user and


redisplays the string after removing vowel from it
5. Add two matrices using nested lists

6. Clone the list using program using copy(), slice()


,list() and deepcopy()methods
7. Calculate Fib(n) using dictionary

8. Read the contents of file and calculate the


percentage of vowels and consonants in the file
9. Program to take command line arguments (word
count)
10. Write a program that prompts the user to enter a
number. If the number is positive or zero print it
or raise an exception
11. Create a class Account. Write methods to
withdraw and deposit amount in the account
12. Create an abstract class polygon. Derive two
classes Rectangle and Triangle from polygon and
write methods to get the details of their
dimensions and calculate the area.

3
Ex.No : 1a
SWAP THE VALUES OF TWO VARIABLES
DATE:

AIM :
To write the python program to swap the value of two variables

ALGORITHM :
1. Take two numbers from the user.
2. x = input('Enter value of x: ')
3. y = input('Enter value of y: ')
4. create a temporary variable and swap the values.
5. Exit.

PROGRAM :

x = int(input('Enter value of x: '))


y= int(input('Enter value of y: '))
temp = x
x =y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y afterswapping: {}'.format(y))

OUTPUT :

RESULT :
Thus the program swap the values of two variables has been successfully implemented.

4
Ex.No :1b
DISTANCE BETWEEN TWO POINTS
DATE:

AIM :
To write the python program to find distance between 2 points.

ALGORITHM:
1. Start the program.
2. Read Coordinates of 1st and 2nd points.
3. Compute the distance using the formula ((((x2 - x1)**2) + ((y2- y1) **2))**0.5)
4. Print Distance.
5. Stop the program.

PROGRAM:

x1=int(input("Enter x1: "))


y1=int(input("Enter y1: "))
x2=int(input("Enter x2: "))
y2=int(input("Enter y2: "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("Distance between",(x1,y1),"and",(x2,y2),"is : ",result)

OUTPUT :

RESULT :
Thus the python program to calculate distance between two points was implemented and
executed successfully

5
Ex.No :2
FIND THE GRADE OF STUDENTS USING THE MARKS
DATE: SCORED IN ALL SUBJECTS

AIM :

To write the python program to find the grade of students using the marks scored in 5 subjects and
basedon Marks obtained in n number of Subjects.

ALGORITHM:

1. Start.

2. Get the marks obtained in 5 subjects from the user.

3. Calculate the total marks for 5 subjects.

4. Calculate the average marks to find the grade according to the average marks obtained

by the student. The grade must be calculated as per following rules:

Average Mark Grade

91-100 A1

81-90 A2

71-80 B1

61-70 B2

51-60 C1

41-50 C2

33-40 D

21-32 E1

0-20 E2

5. Print the grade of students.


6. End.

6
PROGRAM :

print("Enter Marks Obtained in 5 Subjects")


m1 = int(input("ENTER THE MARK 1:"))

m2 = int(input("ENTER THE MARK 2:"))


m3 = int(input("ENTER THE MARK 3:"))
m4 = int(input("ENTER THE MARK 4:"))
m5 = int(input("ENTER THE MARK 5:"))
tot = m1+m2+m3+m4+m5 avg = tot/5
if (avg>=91 and avg<=100):
print("Your Grade is A1")
elif (avg>=81 and avg<=90):
print("Your Grade is A2")
elif (avg>=71 and avg<=80):
print("Your Grade is B1")
elif (avg>=61 and avg<=70):
print("Your Grade is B2")
elif (avg>=51 and avg<=60):
print("Your Grade is C1")
elif (avg>=41 and avg<=50):
print("Your Grade is C2")
elif (avg>=31 and avg<=40):
print("Your Grade is D")
elif (avg>=21 and avg<=30):
print("Your Grade is E1")
elif (avg>=0 and avg<=20):
print("Your Grade is E2")
else: print("Invalid Input!")

FOR LOOP

mark = [] tot = 0 print("Enter Marks Obtained in 5 Subjects:")


for i in range(5): mark.insert(i,input())
for i in range(5):
tot = tot + int(mark[i])
7
avg = tot/5
if (avg>=91 and avg<=100):
print("Your Grade is A1")
elif (avg>=81 and avg<=90):
print("Your Grade is A2")
elif (avg>=71 and avg<=80):
print("Your Grade is B1")
elif (avg>=61 and avg<=70):
print("Your Grade is B2")
elif (avg>=51 and avg<=60):
print("Your Grade is C1")
elif (avg>=41 and avg<=50):
print("Your Grade is C2")
elif (avg>=31 and avg<=40):
print("Your Grade is D")
elif (avg>=21 and avg<=30):
print("Your Grade is E1")
elif (avg>=0 and avg<=20):
print("Your Grade is E2")
else: print("Invalid Input!")

OUTPUT :

RESULT :
Thus the program to find the grade of students using marks obtained in subjects was written and
executed successfully.

8
Ex.No :3a
FIND THE SUM OF SERIES 1/12 +1/22 + …+1/N2
DATE :

AIM :
To write a python program to Find the sum of series 1/12 +1/22 + …+1/N2

ALGORITHM :
1. Take the number of terms n as inputs.
2. Set sum =0 .
3. Add each 1/ i**2 ϵ [1,n] to sum.
4. Display sum as output.

PROGRAM :

n=int(input("Enter the number of terms: "))


sum=0
for i in range(1,n+1):
sum=sum+(1/i**2)
print("The sum of series is",round(sum,2))

OUTPUT :

RESULT :
Thus the python program to find the sum of series was written and executed successfully.

9
Ex.No :3b
CALCULATE GCD USING RECURSIVE FUNCTION
DATE :

AIM :
To write a python program to calculate the greatest common divisor (GCD) of two numbers using
Recursive function

ALGORITHM :

1. Take two numbers from the user.


2. Pass the two numbers as arguments to a recursive function.
3. When the second number becomes 0, return the first number.
4. Else recursively call the function with the arguments as the second number and the remainder.
5. Return the first number which is the GCD of the two numbers.
6. Print the GCD.
7. Exit.

PROGRAM :

def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ",GCD)

OUTPUT :

RESULT :
Thus the program greatest common divisor (GCD) of two numbers using Recursive function has been
successfully implemented
10
Ex.No :4
PROGRAM THAT ACCEPTS A STRING FROMUSER AND
DATE : REDISPLAYS THE STRING AFTER REMOVING VOWEL

AIM :

To write a python Program that accepts a string from the user and redisplays the string after
removing vowels from it.
ALGORITHM :

1. Get the input as a string.


2. Define or initialize a string containing the vowels i.e., a, e, i, o, u.
3. Traverse through the input string, if the vowel is encountered, it should be removed from the
string.
4. Another way is to initialize another string and copy each non-vowel character to this string from
the input string.
5. Display the final result string.

PROGRAM :

def remove_vowels(s):
new_str=" "
for i in s:
if i in "aeiouAEIOU":
pass
else:
new_str+=i
print("The String without vowel is:",new_str)
str=input("\nEnter a string:") remove_vowels(str)

OUTPUT :

RESULT:
Thus the python Program that accepts a string from the user and redisplays the string after removing
vowel from it was executed successfully .
11
Ex.No :5
ADD TWO MATRICES USING NESTED LISTS
DATE :

AIM :
To write a python program to add two matrices using nested lists

ALGORITHM :
1. Start the Program.
2. Assign two input variables to store the nested lists.
3. Set a result variable.
4. Perform addition operation using nested for loop.
5. Store the output in the concerned variable.
6. The result is printed in the console.
7. Stop the program.

PROGRAM :
X=[[2,5,4],[1,3,9],[7,6,2]]
Y=[[1,8,5],[7,3,6],[4,0,9]]
result=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(X)):
for j in range(len(Y)):
result[i][j]=X[i][j]+Y[i][j]
for r in result:
print(r)

OUTPUT :

RESULT:
Thus the python program for adding two matrices using nested lists was executed
successfully.
12
Ex.No :6
CLONE THE LIST PROGRAM USING COPY(), SLICE(),
DATE :
LIST() AND DEEPCOPY() METHODS

AIM :

To write a python program to clone the list using program using copy(), slice(), list() and
deepcopy() methods.

ALGORITHM:

1. Take input of the list from the user.


2. Declare a new list.
3. copy the original list to the new list using the copy() /slice() /list() /deepcopy() function.
4. Print the new list.

PROGRAM :
Copy() method -
li=[]
n=int(input("Enter size of list :"))
for i in range(0,n):
e=int(input("Enter element of list :"))
li.append(e)
print("Original list: ",li)
list_copy = li[:]
print("After cloning: ",list_copy)
Copy() method Output :

13
Slice() method –

import time
my_list = [11,12,13,14,15]
copy_list = my_list[:]
print('Old List:',my_list)
print('New List:',copy_list)

Slice() method Output :

List() method -

li=[]
n=int(input("Enter size of list :"))
for i in range(0,n):
e=int(input("Enter element of list :"))
li.append(e)
print("Original list: ",li)
list_copy = list(li)
print("After cloning: ",list_copy)
List() method Output :

14
Deepcopy() method –
import copy
old_list = [[11, 21, 31], [12, 22, 32], [13, 23, 33]]
new_list = copy.deepcopy(old_list)
print("Old list:", old_list)
print("New list:", new_list)
Deepcopy() method

OUTPUT :

RESULT :
Thus the python program to Clone the list using copy(), slice(), list() and deepcopy() methods
has been written successfully.

15
Ex.No :7
CALCULATE FIB(N) USING DICTIONARY
DATE :

AIM :
To write a python program to Calculate Fib(N) using a dictionary.

ALGORITHM :

1. Take the number n as input using a dictionary.


2. Set n=0.
3. Calculate values fibo(n-1)+fibo(n-2).
4. Display fib(N) as output.

PROGRAM:

Dict={0:0, 1:1}
def fibo(n):
if n not in Dict:
val=fibo(n-1)+fibo(n-2)
Dict[n]=val
return Dict[n]
n=int(input("Enter the value of n:"))

print("Fibonacci(", n,")= ", fibo(n))

OUTPUT :

RESULT :
Thus the python program for Calculate Fib(n) using dictionary was executed successfully.
16
Ex.No :8
READ THE CONTENTS OF THE FILE AND CALCULATE
DATE :
THE PERCENTAGE OF VOWELS AND CONSONANTS

AIM:
To write a python program to read the contents of the file and calculate the percentage of vowels
and consonants in the file.

ALGORITHM :

1. Read the content of the given text file.


2. Split the content of the file into characters.
3. Check each character is a consonant or vowel.
4. Finally the number of vowels and consonants are displayed.

PROGRAM:

print("Enter the Name of File: ") fileName = str(input()) try:


fileHandle = open(fileName, "r")
tot1 = 0 tot2 = 0
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for char in fileHandle.read():
if char in vowels:
tot1 = tot1+1
if char>='a' and char<='z':
if char not in vowels:
tot2 = tot2+1
elif char>='A' and char<='Z':
if char not in vowels:
tot2 = tot2+1
fileHandle.close()
print("The number of Vowels is:",tot1,"\nThe number of consonants is:",tot2)
except IOError:
print("\nError Occurred!")
print("Either File doesn't Exist or Permission is not Allowed!")

17
OUTPUT :

abc.txt-

Gokula Karthikeyan aeiou

RESULT :
Thus the contents of file has been read and the percentage of vowels and consonants in
thefile are executed and output was verified successfully.

18
Ex.No :9
COMMAND LINE ARGUMENT
DATE :

AIM:
To write a python program to state command line argument(word count)

ALGORTHM:
1. start

2. open file in read mode file-open(sys.argv[1],"r+")

3. add arguments to find the words and lines


4. create a set wordcount wordcount=0
5. read the word in file and then split() for word in file.read().split():

6. if word not in wordcount assign 1 to word count else increment word count if word not in wordcount:

wordcount[word]=1 else: Wordcount[word]+=1


7. stop

PROGRAM:
import sys
file-open(sys.argv[1],”r+”)
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word]=1
else:
wordcount[word]+=1
print(word,wordcount)

file.close()

OUTPUT:
C:\user\admin>cd desktop
C:\user\admin\Desktop>py command.py sys.txt
command('the':1, 'tale': 1,'of':1, 'naruto':1}
RESULT:
Thus the program to state command line arguments (word count) has been written
and verified successfully

19
Ex.No :10
TRY AND RAISE AN EXCEPTION
DATE :

AIM:

To write a python program that prompts the user to enter a number. If the number is positive or
zero print it orraise an exception.
ALGORITHM:

1. Start the program

2. Input the number,positive or negative.

3. If number is positive,negative or zero print statements respectively

4. If number is negative raise an exception.

5. Stop.

PROGRAM:
try:

number=int("enter the number:")

if(age<0):

raise value error("number cannot be negative")

except value error:

print("you have entered incorect number")


else:
print("your number is: ,n")

OUTPUT:
enter the number:-5

you have entered incorrect number

enter the number:8

your number is positive

RESULT:
Thus the program to try and raise an exception was executed successfully.

20
Ex.No :11
PROGRAM TO CREATE CLASS ACCOUNT
DATE :

AIM:
To write a python program to create class Account. Write methods to withdraw and deposit amount in
the account.
ALGORITHM:

1. start the program

2. declare the class account

3. declare the funtion init () to create the account

4. declare the deposit() function to deposit the money

5. declare the withdraw() function to withdraw the money

6. now create an object for class account to call the function

7. stop the program

PROGRAM:

class Bank_Account:

def _init_(self):

self.balance=0

def deposit(self):

amount=float(input("Enter amount to be Deposited: "))

self.balance += amount

print("\n Amount Deposited:",amount)

def withdraw(self):

amount = float(input("Enter amount to be Withdrawn: "))

if self.balance>=amount:
21
self.balance-=amount

print("\n You Withdrew:", amount)

else:

print("\n Insufficient balance ")

def display(self):

print("\n Net Available Balance=",self.balance)

s = Bank_Account()

s.deposit()

s.withdraw()

s.display()

OUTPUT:

Enter amount to be deposited:

Amount Deposited: 1000.0

Enter amount to be withdrawn:

You Withdrew: 500.0

Net Available Balance = 500.0

RESULT:
Thus the program to deposit and withdraw the money from bank account is implemented and
executed ,successfully.

22
Ex.No :12
PROGRAM TO CREATE AN ABSTRACT CLASS POLYGON
DATE :

AIM:
To write a python program to create an abstract class polygon. Derive two classes Rectangle
and Triangle frompolygon and write methods to get the details of their dimensions and calculate the
area.

ALGORITHM:
1. start

2. create class polygon

3. Derive two classes Rectangle and Triangle from polygon.

4. Write methods to get the details of their dimensions and calculate the area

5. Print the output

6. Stop.

PROGRAM:
from abc import ABC, abstractmethod

class polygon(ABC):

@abstractmethod
def area1(self):
pass

class triangle(polygon):

def init (self):


self.height = int(input("enter height: "))
self.base = int(input("enter base: "))
def area1(self):
self.area = 1/2 * self.height * self.base

print("area of the triangle is ", self.area)

23
class rectangle(polygon):
def init (self):
self.length = int(input("enter length: "))
self.breadth = int(input("enter breadth: "))
def area1(self):
self.area =self.length * self.breadth
print("area of the rectangle is ", self.area)
r = triangle()
r.area1()
r = rectangle()
r.area1()

Output:

RESULT:
Thus the program to create an abstract class polygon was executed successfully.

24

You might also like