Uploaded by N Fathima Shrene Shifna

Python Programming lab manual (1)

advertisement
173, Agaram Road, Selaiyur, Chennai-600073
BHARATH INSTITUTE OF HIGHER EDUCATION & RESEARCH
Department of Computer Science & Engineering
PYTHON PROGRAMMING
PRACTICAL LAB RECORD
SUB CODE: U20CSCJ03
Name :
Year :
Semester :
Section :
University Register No. :
1
173, Agaram Road, Selaiyur, Chennai-600073
Department of Computer Science & Engineering
SUB CODE / NAME : 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
(Dr.S Maruthuperumal)
Submitted for the practical Examination held on
Institute of Higher Education & Research.
Signature of Internal Examiner
(Date of Exam) At Bharath
Signature of External Examiner
Name:
Name
2
INDEX
S.NO
NAME OF THE PROGRAM
PAGE
NO.
1.
Swap the values of two variables
4
2.
Calculate distance between two
points
Find the grade of student using the
marks scored in all subjects
Find the sum of series 1/12 +1/22 +
…+1/N2
Calculate GCD using recursive
function
Program that accepts a string from
user and redisplays the string after
removing vowel from it
Add two matrices using nested lists
5
3.
4.
5.
6.
7.
8.
9.
10.
DATE OF
COMPLETION
6-8
9
10-11
12-13
14
Clone the list using program using
copy(), slice() ,list() and deepcopy()
methods
Calculate Fib(n) using dictionary
15-17
Read the contents of file and
calculate the percentage of vowels
and consonants in the file
19-20
3
18
SIGNATURE
OF
FACULTY
Ex No : 1
Swap the Values of Two Variables
Date :
Aim : To python program to swap two variables
Algorithm :
1.
2.
3.
4.
5.
Take two numbers from the user.
x = input('Enter value of x: ')
y = input('Enter value of y: ')
create a temporary variable and swap the values.
Exit.
Program :
x=5
y = 10
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Output :
Result : Thus the program swap the values of two variables has been
successfully implemented.
4
Ex No : 2
Distance Between Two Points
Date :
Aim : To write a 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 : 3
Find the Grade of Students Using The Marks Scored In All Subjects
Date :
Aim : To write the program to find the grade of students using the marks
scored in 5 subjects and based on Marks obtained in n number of Subjects.
Algorithm:
1.
2.
3.
4.
Start.
Get the marks obtained in 5 subjects from the user.
Calculate the total marks for 5 subjects.
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.
Program :
print("Enter Marks Obtained in 5 Subjects")
m1 = int(input("ENTER THE MARK 1:"))
m2 = int(input("ENTER THE MARK 2:"))
6
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<=91):
print("Your Grade is A2")
elif (avg>=71 and avg<=81):
print("Your Grade is B1")
elif (avg>=61 and avg<=71):
print("Your Grade is B2")
elif (avg>=51 and avg<=61):
print("Your Grade is C1")
elif (avg>=41 and avg<=51):
print("Your Grade is C2")
elif (avg>=33 and avg<=41):
print("Your Grade is D")
elif (avg>=21 and avg<=33):
print("Your Grade is E1")
elif (avg>=0 and avg<=21):
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])
avg = tot/5
if (avg>=91 and avg<=100):
print("Your Grade is A1")
elif (avg>=81 and avg<=91):
print("Your Grade is A2")
7
elif (avg>=71 and avg<=81):
print("Your Grade is B1")
elif (avg>=61 and avg<=71):
print("Your Grade is B2")
elif (avg>=51 and avg<=61):
print("Your Grade is C1")
elif (avg>=41 and avg<=51):
print("Your Grade is C2")
elif (avg>=33 and avg<=41):
print("Your Grade is D")
elif (avg>=21 and avg<=33):
print("Your Grade is E1")
elif (avg>=0 and avg<=21):
print("Your Grade is E2")
else:
print("Invalid Input!")
Output :
Result : Thus the program to find the grade of students using the marks
scored in 5 subjects and based on Marks obtained in n number of Subjects
was written and executed successfully.
8
Ex No : 4
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 ϵ [1,n], to sum.
4. Display sum as output.
Program :
n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))
Output :
Result : Thus the python program to find the sum of series was written and
executed successfully.
9
Ex No : 5
Calculate Gcd Using Recursive Function
Date :
Aim : To calculate the greatest common divisor (GCD) of two numbers using
Recursive function
Algorithm :
1.
2.
3.
4.
Take two numbers from the user.
Pass the two numbers as arguments to a recursive function.
When the second number becomes 0, return the first number.
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 :
10
Result : Thus the program greatest common divisor (GCD) of two numbers
using Recursive function has been successfully implemented.
11
Ex No : 6
Calculate GCD using recursive function
Date :
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 :
12
Result: Thus the python Program that accepts a string from the user and
redisplays the string after removing vowel from it was successfully using
Python IDLE.
13
Ex No : 7
Add Two Matrices using Nested Lists
Date :
Aim : To write a python program to add two matrices using nested lists
Algorithm :
1.
2.
3.
4.
5.
6.
7.
Start the Program.
Assign two input variables to store the nested lists.
Set a result variable.
Perform addition operation using nested for loop.
Store the output in the concerned variable.
The result is printed in the console.
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.
14
Ex No : 8
Clone the list Program using copy(), slice(), list() and deepcopy()
methods
Date :
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 :
15
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)
16
List() method Output :
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.
17
Ex No : 9
Calculate Fib(n) using dictionary
Date :
Aim : To write a python program to Calculate Fib(N) using a dictionary.
Algorithm :
1.
2.
3.
4.
Take the number n as input using a dictionary.
Set n=0.
Calculate values fibo(n-1)+fibo(n-2).
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.
18
Ex No : 10
Read the contents of the file and calculate the percentage of vowels
and consonants in the file.
Date :
Aim: To read the contents of the file and calculate the percentage of vowels
and consonants in the file.
Algorithm :
1.
2.
3.
4.
Read the content of the given text file.
Split the content of the file into characters.
Check each character is a consonant or vowel.
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!")
19
Output :
abc.txtGokula Karthikeyan
aeiou
Result : Thus the contents of file has been read and the percentage of
vowels and consonants in the file are executed and output was verified
successfully.
20
Related documents
Download