INDEX
MC4112 - Python Programming Laboratory
EXP. DATE EXPERIMENT PAG SIGN
NO E
NO.
1. PYTHON PROGRAMMING USING SIMPLE STATEMENT AND
EXPRESSIONS(EXCHANGE THE VALUES OF TWO VARIABLES,CIRCULATE THE
VALUES OF N VARIABLES, DISTANCE BETWEEN TWO POINT).
1.1 Exchange the values of two variables with
temporary variable
1.2 Exchange the values of two variables without
temporary variable
1.3 Distance between two points
1.4 Circulate the values of n variables
2. SCIENTIFIC PROBLEM USING CONDITIONAL AND ITERATIVE LOOPS.
2.1 To find a given number odd or even
2.2 To find biggest amoung three number
2.3 To get five subject mark and display the grade
2.4 To find given number is armstrong number or not
using while loop
2.5 To print the factorial a number using for loop
2.6 To construct the following pattern using Nested loop
3. LINEAR SEARCH AND BINARY SEARCH
3.1 Linear Search
3.2 Binary Search
4. SELECTION SORT AND INSERTION SORT
4.1 Selection sort
4.2 Insertion sort
5. MERGE SORT AND QUICK SORT
5.1 Merge sort
5.2 Quick sort
6. IMPLEMENTING APPLICATIONS USING LISTS, TUPLE
6.1 To Display append,reverse,pop in a list
6.2 Program for Slicing a list
6.3 To find Minimum and Maximum number in tuple
6.4 To interchange two values using tuple assigment
7. IMPLEMENT APPLICATION USING SETS, DICTIONARIES
7.1 To display sum of element,add element and remove
element in the set
7.2 To display Intersection of element and difference of
element in set
7.3 To sum of all items in a dictionary
7.4 To updating a element in dictionary
8. IMPLEMENTING PROGRAM USING FUNCTION
8.1 To calculate the area of a triangle using with
argument and with return type
8.2 To greatest common divisor using with argument
and without return type
8.3 To factorial of given number using Regreression
function
9. IMPLEMENTING PROGRAM USING STRING
9.1 To count the number of vowels and consonants in
the string
9.2 To check given string is palindrome or not
9.3 To read N names and sort name in alphabetic order
using string
10. IMPLEMENTING PROGRAM USING WRITEN MODULE AND PYTHON
STANDARD LIBRARIES(PANDAS,NUMPY,MATHPLOTLIB,SCIPY)
10.1 To operation Numpy With Array
10.2 Dataframe from three series using pandas
10.3 Program to line Chart-matplotlib
10.4 Program to Using Scipy
11. IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USINGFILE
HANDLING.
11.1 Program to count total number of uppercase and
lowercase charater in a file
11.2 Program to merging two file
12. IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USINGEXCEPTION
HANDLING
12.1 Python program of zero division Error
12.2 Program to Exception for eligible for vote
12.3 Program to multiple Exception handling
13. CREATING AND INSTANTIATING CLASSES
13.1 write a python program to display the
student details using class
EX:1.1
Exchange the values of two variables with temporary
variable
PROGRAM:
print("Exchange the values of two variables with temporary ")
x=int(input("Enter a value of x:"))
y=int(input("Enter a value of y:"))
print("Before Swapping :")
print("The value of x : ",x,"and y : ",y)
temp=x
x=y
y=temp
print("After Swapping :")
print("The value of x : ",x,"and y : ",y)
OUTPUT 1:
Exchange the values of two variables with temporary
Enter a value of x:2
Enter a value of y:4
Before Swapping :
The value of x : 2 and y : 4
After Swapping :
The value of x : 4 and y : 2
EXNO:1.2
Exchange the values of two variables without temporary variable
PROGRAM:
print("Exchange the values of two variables without temporary variable")
x=int(input("Enter a value of x:"))
y=int(input("Enter a value of y:"))
print("Before Swapping :")
print("The value of x : ",x,"and y : ",y)
x,y=y,x
print("After Swapping :")
print("The value of x : ",x,"and y : ",y)
Output:
Exchange the values of two variables without temporary variable
Enter a value of x:20
Enter a value of y:30
Before Swapping :
The value of x : 20 and y : 30
After Swapping :
The value of x : 30 and y : 20
EXNO:1.3
Calculate Distance between two points
Program :
import math
print("Calculating Distance Between Two Points")
x1=int(input("Enter x1 value :"))
x2=int(input("Enter x2 value :"))
y1=int(input("Enter y1 value :"))
y2=int(input("Enter y2 value :"))
ans=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance Between Two Point is :",ans)
Output:
Calculating Distance Between Two Points
Enter x1 value :10
Enter x2 value :32
Enter y1 value :5
Enter y2 value :6
Distance Between Two Point is : 22.02271554554524
EXNO1.4
Circulate the values of n variable
Program :
no_of_terms=int(input("Enter numbers of values:"))
list1=[]
for val in range(0,no_of_terms,1):
ele=int(input("Enter integer:"))
list1.append(ele)
print("Circulating the elements of list:",list1)
for val in range(0,no_of_terms,1):
ele=list1.pop(0)
list1.append(ele)
print(list1)
Output:
Enter numbers of values:4
Enter integer:10
Enter integer:20
Enter integer:30
Enter integer:40
Circulating the elements of list: [10, 20, 30, 40]
[20, 30, 40, 10]
[30, 40, 10, 20]
[40, 10, 20, 30]
[10, 20, 30, 40]
EXNO:2.1
TO FIND ODD OR EVEN NUMBER IN PYTHON
PROGRAM:
print("\t\tTO FIND ODD OR EVEN NUMBER IN PYTHON")
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num,"is Even number")
else:
print(num," is Odd number")
Output 1:
TO FIND ODD OR EVEN NUMBER IN PYTHON
Enter a number: 20
20 is Even number
Output 2:
TO FIND ODD OR EVEN NUMBER IN PYTHON
Enter a number: 71
71 is Odd number
EXNO:2.2
TO FIND BIGGEST AMOUNG THREE NUMBERS
PROGRAM:
print("\t\tTO FIND BIGGEST AMOUNG THREE NUMBERS")
a=int(input("Enter the 1st number :"))
b=int(input("Enter the 2nd number :"))
c=int(input("Enter the 3rd number :"))
if (a>b)and (a>c):
print(a,"is largest")
elif (b>c):
print(b,"is largest")
else:
print(c,"is largest")
Output:
TO FIND BIGGEST AMOUNG THREE NUMBERS
Enter the 1st number :10
Enter the 2nd number :400
Enter the 3rd number :3000
3000 is largest
EX.NO: 2.3
To Get Five Subject Mark And Display The Grade
Program:
print("\t\tTo Get Five Subject Mark And Display The Grade")
m1=int(input("Enter m1 mark :"))
m2=int(input("Enter m2 mark :"))
m3=int(input("Enter m3 mark :"))
m4=int(input("Enter m4 mark :"))
m5=int(input("Enter m5 mark :"))
total =m1+m2+m3+m4+m5
avg=(total/5)
print("Total :",total)
print("Average :",avg)
if m1>49 and m2>49 and m3>49 and m4>49 and m5>49:
print("Pass")
if avg>=50 and avg<60:
print("2nd class")
elif avg>=60 and avg<70:
print("1st class")
else:
print(" 1st class Distinction")
else:
print("No Grade")
OUTPUT:
To Get Five Subject Mark And Display The Grade
Enter m1 mark :89
Enter m2 mark :66
Enter m3 mark :88
Enter m4 mark :90
Enter m5 mark :99
Total : 432
Average : 86.4
Pass
1st class Distinction
EXNO:2.4
TO FIND A AMSTRONG NUMBER
PROGRAM:
print("TO FIND A AMSTRONG NUMBER")
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is a Armstrong number")
else:
print(num,"is not a Armstrong number")
OUTPUT 1:
TO FIND A AMSTRONG NUMBER
Enter a number: 370
370 is a Armstrong number
OUTPUT 2:
TO FIND A AMSTRONG NUMBER
Enter a number: 675
675 is not a Armstrong number
EX.NO:2.5
TO FIND THE FACTORIAL OF GIVEN NUMBER
PROGRAM:
print("To Find The Factorial Of Given Number")
n=int(input("Enter a Number :"))
f=1
for i in range(1,n+1):
f=f*i
print(f)
OUTPUT 1:
To Find The Factorial Of Given Number
Enter a Number :5
120
OUTPUT 2:
To Find The Factorial Of Given Number
Enter a Number :7
5040
EXNO:2.6
TO PRINT A STAR PATTERN USING NESTED FOR LOOP
PROGRAM:
rows = int(input("Please Enter the Total Number of Rows : "))
print("Right Angled Triangle Star Pattern")
for i in range(1, rows + 1):
for j in range(1, i + 1):
print('*', end = ' ')
print()
OUTPUT:
Please Enter the Total Number of Rows : 6
Right Angled Triangle Star Pattern
**
***
****
*****
******
EXNO:3.1
LINER SEARCH
PROGRAM :
def linearSearch(array, n, x):
for i in range(0, n):
if(array[i]==x):
return i
return -1
list1=[]
a=int(input("Enter How many Value :"))
print("Enter a Element :")
for i in range(1,a+1):
c=int(input())
list1.append(c)
x=int(input("Enter a number to find : "))
n=len(list1)
result = linearSearch(list1, n, x)
if(result == -1):
print("Element not found",result)
else:
print("Element found at index:",result)
OUTPUT :1
Enter How many Value :5
Enter a Element :
Enter a number to find : 3
Element found at index: 2
OUTPUT :2
Enter How many Value :5
Enter a Element :
Enter a number to find : 6
Element not found -1
EXNO:3.2
BINARY SEARCH
PROGRAM :
def binary_search(list1, n):
low = 0
high = len(list1)-1
mid = 0
while low <= high:
mid = (high + low) // 2
if list1[mid] < n:
low = mid + 1
elif list1[mid] > n:
high = mid-1
else:
return mid
return -1
list1=[]
x=int(input("Enter How many value :"))
print("Enter The Element :")
for i in range(1,x+1):
a=int(input())
list1.append(a)
n = int(input("Enter a Elements to find : "))
result = binary_search(list1, n)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")
OUTPUT :1
Enter How many value :5
Enter The Element :
10
20
30
40
50
Enter a Elements to find : 30
Element is present at index 2
OUTPUT :2
Enter How many value :5
Enter The Element :
50
60
70
80
90
Enter a Elements to find : 100
Element is not present in list1
EXNO:4.1
Selection Sort
PROGRAM :
def selectionsort(array,size):
for step in range(size):
min_idx=step
for i in range(step+1,size):
if array[i]<array[min_idx]:
min_idx=i
(array[step],array[min_idx])=(array[min_idx],array[step])
data=[]
p=int(input("Number of elements: "))
for i in range(0,p):
l=int(input())
data.append(l)
print("Before sorted list:",data)
size=len(data)
selectionsort(data,size)
print("After sorted list using selection sort:",data)
OUTPUT :
Number of elements: 6
50
40
30
20
10
Before sorted list: [50,40,30,20,10]
After sorted list using selection sort: [10,20,30,40,50]
EXNO:4.2
Insertion Sort
PROGRAM:
def insertionsort(array):
for step in range(1,len(array)):
key=array[step]
j=step-1
while j>=0 and key<array[j]:
array[j+1]=array[j]
j=j-1
array[j+1]=key
data=[]
p=int(input("Number of elements: "))
for i in range(0,p):
l=int(input())
data.append(l)
print("Before sorted array:",data)
insertionsort(data)
print("After sorted array using insertion sort :",data)
OUTPUT :
Number of elements: 6
Before sorted array: [5,4,3,2,1]
After sorted array using insertion sort : [1,2,3,4,5]
EXNO:5.1
Merge Sort
PROGRAM :
def mergeSort(array):
if len(array) > 1:
r = len(array)//2
L = array[:r]
M = array[r:]
mergeSort(L)
mergeSort(M)
i=j=k=0
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1
while i < len(L):
array[k] = L[i]
i += 1
k += 1
while j < len(M):
array[k] = M[j]
j += 1
k += 1
def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
array = []
p=int(input("Number of elements: "))
print("Enter The Element :")
for i in range(0,p):
l=int(input())
array.append(l)
print("Before sorted array : ",array)
mergeSort(array)
print("Sorted array using merge sort: ",array)
OUTPUT :
Number of elements: 4
Enter The Element :
78
56
34
-2
Before sorted array : [78, 56, 34, -2]
Sorted array using merge sort: [-2, 34, 56, 78]
EXNO:5.2
QUICK SORT
PROGRAM :
def partition(array, low, high):
pivot = array[high]
i = low - 1
for j in range(low, high):
if array[j] <= pivot:
i=i+1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1
def quickSort(array, low, high):
if low < high:
pi = partition(array, low, high)
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)
data=[]
n=int(input("Number of elements: "))
for i in range(0,n):
l=int(input())
data.append(l)
print("Before sorted list:",data)
quickSort(data, 0, n- 1)
print('Sorted Array using quicksort:',data)
OUTPUT :
Number of elements: 6
60
50
40
30
20
10
Before sorted list: [60,50,40,30,20,10]
Sorted Array using quicksort: [10,20,30,40,50,60]
EX.NO:6.1
TO FIND APPEND , REVERSE AND POP IN A LIST
PROGRAM:
print("\t\tTo Find Append , Reverse And Pop In a List")
print()
print("\t\t Append in List")
n=int(input("Enter how Many Value :"))
list1=[]
print("Enter List Element :")
for I in range(1,n+1):
a=int(input())
list1.append(a)
print("Before Appending ",list1)
x=int(input("Enter Adding Element :"))
list1.append(x)
print("After Appending ",list1)
print()
print("\t\tReverse in List")
list2=[]
n=int(input("Enter how Many Value :"))
print("Enter List Element :")
for I in range(1,n+1):
a=int(input())
list2.append(a)
print("Before Reverse ",list2)
list2.reverse()
print("After reverse ",list2)
print()
print("\t\tPop in List Element")
list3=[]
n=int(input("Enter how Many Value :"))
print("Enter List Element :")
for I in range(1,n+1):
a=int(input())
list3.append(a)
print("Before pop in list ",list3)
print("Enter poping Element Index :")
p=int(input())
list3.pop(p)
print("After pop in List ",list3)
OUTPUT:
To Find Append , Reverse And Pop In a List
Append in List
Enter how Many Value :4
Enter List Element :
10
20
30
40
Before Appending [10, 20, 30, 40]
Enter Adding Element :50
After Appending [10, 20, 30, 40, 50]
Reverse in List
Enter how Many Value :5
Enter List Element :
Before Reverse [4, 3, 2, 1, 0]
After reverse [0, 1, 2, 3, 4]
Pop in List Element
Enter how Many Value :4
Enter List Element :
100
200
300
400
Before pop in list [100, 200, 300, 400]
Enter poping Element Index :
After pop in List [200, 300, 400]
EX.NO: 6.2
PROGRAM FOR SLICING LIST
PROGRAM:
print("\t\tProgram For Slicing List")
print()
n=int(input("Enter how Many Value :"))
list1=[]
print("Enter List Element :")
for I in range(1,n+1):
a=int(input())
list1.append(a)
print("list is ",list1 )
print("Index 0 to 3 :",list1[0:4])
print("Index 3 to 5 :",list1[3:6])
print("Index To print Reverse :",list1[::-1])
print("Last Element in List :",list1[-1])
OUTPUT :
Program For Slicing List
Enter how Many Value :5
Enter List Element :
12
13
14
15
16
list is [12, 13, 14, 15, 16]
Index 0 to 3 : [12, 13, 14, 15]
Index 3 to 5 : [15, 16]
Index To print Reverse : [16, 15, 14, 13, 12]
Last Element in List : 16
EX.NO: 6.3
TO DISPLAY THE MAXIMUM AND MINIMUM VALUE IN
THE TUPLE
PROGRAM:
print("To Display The Maximum And Minimum\n")
n=int(input("Enter how Many Value :"))
list1=[]
print("Enter List Element :")
for I in range(1,n+1):
a=int(input())
list1.append(a)
a=tuple(list1)
print("Tuple is ",a)
highest=max(a)
print("Highest value is ",highest)
low=min(a)
print("Lowest value is ",low)
OUTPUT :
To Display The Maximum And Minimum
Enter how Many Value :5
Enter List Element :
10
200
34
32
66
Tuple is (10, 200, 34, 32, 66)
Highest value is 200
Lowest value is 10
EXNO:6.4
TO INTERCHANGE TWO VALUES USING TUPLE ASSIGNMENT
PROGRAM :
print("\t\t To Interchange Two Values Using Tuple Assignment")
a = int(input("Enter value of A: "))
b = int(input("Enter value of B: "))
print("Before swap tuple Value of A = ",a," Value of B = " , b)
(a, b) = (b, a)
print("After swap tuple Value of A = ", a," Value of B = ", b)
OUTPUT :
To Interchange Two Values Using Tuple Assignment
Enter value of A: 45
Enter value of B: 75
Before swap tuple Value of A = 45 Value of B = 75
After swap tuple Value of A = 75 Value of B = 45
EX.NO: 7.1
TO DISPLAY SUM OF ELEMENT ADD ELEMENT AND
REMOVE ELEMENT IN THE SET
PROGRAM:
print("To Display Sum Of Element , Add Element And Remove Element In The Set")
n=int(input("Enter how Many Value :"))
list1=[]
print("Enter List Element :")
for I in range(1,n+1):
a=int(input())
list1.append(a)
a=set(list1)
print()
print("Set a value is :",a)
sum_set=sum(a)
print("Sum of Element In Set :",sum_set)
print()
print("Before Adding set ",a)
print("Enter Adding Element :")
b=int(input())
a.add(b)
print("After Adding Set ",a)
print()
print("Before Remove Element in Set ",a)
print("Enter Remove Element :")
b=int(input())
a.remove(b)
print("After Remove Element in set ",a)
Output:
To Display Sum Of Element , Add Element And Remove Element In The Set
Enter how Many Value :5
Enter List Element :
Set a value is : {1, 2, 3, 4, 5}
Sum of Element In Set : 15
Before Adding set {1, 2, 3, 4, 5}
Enter Adding Element :
After Adding Set {1, 2, 3, 4, 5, 6}
Before Remove Element in Set {1, 2, 3, 4, 5, 6}
Enter Remove Element :
After Remove Element in set {2, 3, 4, 5, 6}
EX.NO: 7.2
TO DISPLAY INTERSECTION OF ELEMENT AND
DIFFERENCE OF ELEMENT IN THE SET
PROGRAM:
n=int(input("Enter how Many Value :"))
list1=[]
print("Enter Set A Element :")
for i in range(1,n+1):
a=int(input())
list1.append(a)
a1=set(list1)
n=int(input("Enter how Many Value For B set :"))
list2=[]
print("Enter Set B Element :")
for i in range(1,n+1):
a=int(input())
list2.append(a)
b1=set(list2)
print("A set is ",a1)
print("B set is ",b1)
print("Intersection of sets ",a1.intersection(b1))
print("Difference of sets 'a' & 'b' ",a1.difference(b1))
Output:
Enter how Many Value :5
Enter Set A Element :
11
12
13
14
15
Enter how Many Value For B set :5
Enter Set B Element :
14
15
16
17
18
A set is {11, 12, 13, 14, 15}
B set is {14, 15, 16, 17, 18}
Intersection of sets {14, 15}
Difference of sets 'a' & 'b' {11, 12, 13}
EXNO:7.3
TO UPDATING A ELEMENTS IN A DICTONARY
PROGRAM:
Dictionary1 = {}
Dictionary2 = {}
print("\t\tDictionary 1")
n=int(input("Enter How many value :"))
for i in range(0,n):
name=input("Enter Name :")
salary=input("Enter salary :")
Dictionary1[name]=salary
print("Original Dictionary:")
print(Dictionary1)
print("\t\tDictionary 2")
n=int(input("Enter How many value :"))
for i in range(0,n):
name=input("Enter Name :")
salary=input("Enter salary :")
Dictionary2[name]=salary
Dictionary1.update(Dictionary2)
print("Dictionary after updation:")
print(Dictionary1)
OUTPUT:
Dictionary 1
Enter How many value :2
Enter Name :sakthi
Enter salary :20000
Enter Name :baskar
Enter salary :45000
Original Dictionary:
{'sakthi': '20000', 'baskar': '45000'}
Dictionary 2
Enter How many value :1
Enter Name :parthipan
Enter salary :50000
Dictionary after updation:
{'sakthi': '20000', 'baskar': '45000', 'parthipan': '50000'}
EXNO:7.4
SUM OF ALL ITEMS IN A DICTIONARY
Program :
def returnSum1(myDict):
List=[]
for i in myDict:
List.append(myDict[i])
final=sum(List)
return final
def returnSum2(dict):
sum=0
for i in dict.values():
sum=sum+i
return sum
def returnSum3(dict):
sum=0
for i in dict:
sum=sum+dict[i]
return sum
dict={}
n=int(input("Enter How many value :"))
for i in range(0,n):
a=input("Enter keys :")
b=int(input("Enter values :"))
dict[a]=b
print("Dictionary :",dict)
print("Sum in method 1 :",returnSum1(dict))
print("Sum in method 2 :",returnSum2(dict))
print("Sum in method 3 :",returnSum3(dict))
Output :
Enter How many value :3
Enter keys :a
Enter values :10
Enter keys :b
Enter values :20
Enter keys :c
Enter values :30
Dictionary : {'a': 10, 'b': 20, 'c': 30}
Sum in method 1 : 60
Sum in method 2 : 60
Sum in method 3 : 60
EX.NO: 8.1
CALCULATE THE AREA OF A TRIANGLE USING WITH
ARGUMENT WITH RETURN TYPE FUNCTION
PROGRAM:
print("Calaulate The Area Of A Triangle Using\n With Argument With return type\n")
def area_triangle(h,b):
ans=(h*b)/2
return ans
a=int(input("Enter height :"))
b=int(input("Enter base :"))
ans=area_triangle(a,b)
print("Area Of Triangle is ",ans)
OUTPUT :
Calaulate The Area Of A Triangle Using
With Argument With return type
Enter height :10
Enter base :20
Area Of Triangle is 100.0
EXNO:8.2
GREATEST COMMON DIVISOR PROGRAM USING FUNCTION
WITHOUT ARGUMENT & WITH RETURN VALUE
PROGRAM :
print("To Greatest commom Divisor \n\tUsing\nwith Argument Without Return Type Function ")
print()
def GCD_Loop():
gcd=0
a=int(input(" Enter the first number: "))
b=int(input(" Enter the second number: "))
if a > b:
temp = b
else:
temp = a
for i in range(1, temp + 1):
if (( a % i == 0) and (b % i == 0 )):
gcd = i
return gcd
num = GCD_Loop()
print("GCD of two number is: ",num)
OUTPUT :
To Greatest commom Divisor
Using
with Argument Without Return Type Function
Enter the first number: 98
Enter the second number: 56
GCD of two number is: 14
EX.NO: 8.3
TO FACTORIAL OF GIVEN NUMBER USING REGRERESSION
PROGRAM:
print("To Factorial Of Given Number Using Regreression")
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
num=int(input("Enter a number:"))
if num<0:
print("sorry,factorial does not exist for negative numbers")
elif num==0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,'is',factorial(num))
OUTPUT :
To Factorial Of Given Number Using Regreression
Enter a number:7
The factorial of 7 is 5040
EXNO:9.1
PYTHON PROGRAM TO COUNT NUMBER OF VOWELS AND
CONSONANTS IN A STRING
PROGRAM:
str=input("Enter a string : ");
vowels=0
consonants=0
for i in str:
if(i == 'a'or i == 'e'or i == 'i'or i == 'o'or i == 'u' or
i == 'A'or i == 'E'or i == 'I'or i == 'O'or i == 'U' ):
vowels=vowels+1;
else:
consonants=consonants+1;
print("The number of vowels:",vowels);
print("\nThe number of consonant:",consonants);
OUTPUT:
Enter a string : python program
The number of vowels: 3
The number of consonant: 11
EXNO:9.2
PYTHON PROGRAM PALINDROME USING STRING
PROGRAM:
string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The given string is a palindrome")
else:
print("The given string is not a palindrome")
OUTPUT 1:
Enter a letter:sps
The given string is a palindrome
OUTPUT 2:
Enter a letter: class
The given string is not a palindrome
EX.NO: 9.3
TO READ N NAME AND SORT NAME IN ALPHABETIC ORDER
USING STRING
PROGRAM:
print("To Read N Name And Sort Name In Alphabetic Order Using String")
n=int(input("ENTER A HOW MANY VALUE :"))
na=[]
for i in range(n):
a=input("Enter Name :")
na.append(a)
print("Before Sorting ",na)
na.sort()
print("After Sorting ",na)
Output:
To Read N Name And Sort Name In Alphabetic Order Using String
ENTER A HOW MANY VALUE :3
Enter Name :car
Enter Name :zap
Enter Name :xerox
Before Sorting ['car', 'zap', 'xerox']
After Sorting ['car', 'xerox', 'zap']
EX.NO:10.1
TO OPERATION ON NUMPY WITH ARRAY
PROGRAM:
import numpy as np
arr1=[]
print("\t\tEnter Firt Array ")
r=int(input("Enter How Many Row :"))
c=int(input("Enter How Many Coloum :"))
for i in range(r):
b=[]
for j in range(c):
x=int(input("Enter Element :"))
b.append(x)
arr1.append(b)
arra1=np.array(arr1)
print(arra1)
arr2=[]
print("\t\tEnter Second Array ")
r=int(input("Enter How Many Row :"))
c=int(input("Enter How Many Coloum :"))
for i in range(r):
b=[]
for j in range(c):
x=int(input("Enter Element :"))
b.append(x)
arr2.append(b)
arra2=np.array(arr2)
print("\nSecond array:")
print(arra2)
print("\nAdding the two arrays:")
print(np.add(arra1,arra2))
print("\nSubtracting the two arrays:")
print(np.subtract(arra1,arra2))
print('\nMultiplying the two arrays:')
print(np.multiply(arra1,arra2))
print('\nDividing the two arrays:')
print(np.divide(arra1,arra2))
OUTPUT:
Enter Firt Array
Enter How Many Row :2
Enter How Many Coloum :2
Enter Element :1
Enter Element :2
Enter Element :3
Enter Element :4
[[1 2]
[3 4]]
Enter Second Array
Enter How Many Row :2
Enter How Many Coloum :2
Enter Element :4
Enter Element :3
Enter Element :2
Enter Element :1
Second array:
[[4 3]
[2 1]]
Adding the two arrays:
[[5 5]
[5 5]]
Subtracting the two arrays:
[[-3 -1]
[ 1 3]]
Multiplying the two arrays:
[[4 6]
[6 4]]
Dividing the two arrays:
[[0.25 0.66666667]
[1.5 4. ]]
EX.NO:10.2
Dataframe From Three Series Using Pandas
PROGRAM:
import pandas as pd
print("Display Student Details Pandas")
stu = {'Roll_no':[],'Name':[],'Age':[],'Class':[],'Date_of_birth':[]}
while True:
print("\t\tMenu Card\n")
print("1) Adding Student Details ")
print("2) Display Student Details")
print("3) Insert New Categories Place ")
print("4) Drop Coloumn By Name ")
print("5) Exit")
c=int(input("Enter Your Choise :"))
if c==1:
no=int(input("Enter No.Of Student :"))
for i in range(no):
Rool_no=int(input("Enter Rool Number :"))
Name=input("Enter Name :")
Age=int(input("Enter Age :"))
Class=input("Enter Class :")
Date_of_birth=input("Enter Date Of Birth :")
stu['Roll_no'].append(Rool_no)
stu['Name'].append(Name)
stu['Age'].append(Age)
stu['Class'].append(Class)
stu['Date_of_birth'].append(Date_of_birth)
stu = pd.DataFrame(stu)
elif c==2:
print(stu)
elif c==3:
print("Adding new categorie Placce")
x=int(input("Enter Numer Of Iterm :"))
Place = []
for i in range(x):
P = input("Enter Place : ")
Place.append(P)
stu['place'] = Place
print("After Insert New Categories")
print(stu)
elif c==4:
print("Drop Coloumn By Name")
n=input("Enter Drop coloumn Name With correct Spelling :")
stu.drop(str(n), axis=1, inplace=True)
print(stu)
elif c==5:
break
print("Thank you for watching our program !!")
OUTPUT:
Display Student Details Pandas
Menu Card
1) Adding Student Details
2) Display Student Details
3) Insert New Categories Place
4) Drop Coloumn By Name
5) Exit
Enter Your Choise :1
Enter No.Of Student :2
Enter Rool Number :4575
Enter Name :sakthi
Enter Age :23
Enter Class :MCA
Enter Date Of Birth :30-12-2001
Enter Rool Number :1234
Enter Name :parthipan
Enter Age :21
Enter Class :MCA
Enter Date Of Birth :26-12-2001
Menu Card
1) Adding Student Details
2) Display Student Details
3) Insert New Categories Place
4) Drop Coloumn By Name
5) Exit
Enter Your Choise :2
Roll_no Name Age Class Date_of_birth
0 4575 sakthi 23 MCA 30-12-2001
1 1234 parthipan 21 MCA 26-12-2001
Menu Card
1) Adding Student Details
2) Display Student Details
3) Insert New Categories Place
4) Drop Coloumn By Name
5) Exit
Enter Your Choise :3
Adding new categorie Placce
Enter Numer Of Iterm :2
Enter Place : Ariyalur
Enter Place : Karur
After Insert New Categories
Roll_no Name Age Class Date_of_birth place
0 4575 sakthi 23 MCA 30-12-2001 Ariyalur
1 1234 parthipan 21 MCA 26-12-2001 Karur
Menu Card
1) Adding Student Details
2) Display Student Details
3) Insert New Categories Place
4) Drop Coloumn By Name
5) Exit
Enter Your Choise :4
Drop Coloumn By Name
Enter Drop coloumn Name With correct Spelling :Class
Roll_no Name Age Date_of_birth place
0 4575 sakthi 23 30-12-2001 Ariyalur
1 1234 parthipan 21 26-12-2001 Karur
Menu Card
1) Adding Student Details
2) Display Student Details
3) Insert New Categories Place
4) Drop Coloumn By Name
5) Exit
Enter Your Choise :5
Thank you for watching our program !!
EX.NO:10.3
PROGRAM TO LINE CHART-MATPLOTLIB
PROGRAM:
from matplotlib import pyplot as plt
from matplotlib import style
print("Line Chart Using Matplotlib\n")
style.use('ggplot')
x=[]
n=int(input("Enter Limit :"))
print("Enter Element :")
for i in range(n):
a=int(input())
x.append(a)
y=[]
n=int(input("Enter Limit :"))
print("Enter Element :")
for i in range(n):
b=int(input())
y.append(b)
print(x)
print(y)
plt.plot(x,y,'g',label='line one',linewidth=5)
plt.title('Epic Info')
plt.ylabel('y axis')
plt.xlabel('x axis')
plt.legend()
plt.grid(True,color='y')
plt.show()
OUTPUT:
Line Chart Using Matplotlib
Enter Limit :5
Enter Element :
Enter Limit :5
Enter Element :
[4, 3, 4, 5, 4]
[6, 4, 2, 4, 6]
EX.NO:10.4
PROGRAM TO USING SCIPY
PROGRAM:
from scipy import misc,ndimage
import matplotlib.pyplot as plt
face = misc.face()
plt.imshow(face)
plt.show()
rotate_face = ndimage.rotate(face, 45)
plt.imshow(rotate_face)
plt.show()
OUTPUT:
EXNO:11.1
Merging two files
PROGRAM :
def program1():
f = open("python2.txt","w")
para=input("Enter the para for pythonfile :")
newline="\n"
f.write(para)
f.write(newline)
f.close()
def program2():
f = open("Javafile.txt","w")
para=input("Enter the para for Java file :")
newline="\n"
f.write(para)
f.write(newline)
f.close()
def program3():
with open("python2.txt","r") as f1:
data=f1.read()
with open("Javafile.txt","r") as f2:
data1=f2.read()
with open("merge.txt","w") as f3:
f3.write(data)
f3.write(data1)
f3.close()
program1()
print("Writing File1 Succussful")
program2()
print("Writing File2 Succussful")
program3()
print("Writing File3 Succussful")
OUTPUT:
Enter the para for pythonfile :we can import python module
Writing File1 Succussful
Enter the para for Java file :directory must contain
Writing File2 Succussful
Writing File3 Succussful
EXNO:11.2
To Count The Upper Case , Lower Case & Digits In A File
PROGRAM :
def filecreation():
f = open("pythonfile.txt","w")
line=input("Type a para maximum 2 lines :")
new_line="\n"
f.write(line)
f.write(new_line)
f.close()
def operation():
with open("pythonfile.txt","r") as f1:
data=f1.read()
cnt_ucase =0
cnt_lcase=0
cnt_digits=0
for ch in data:
if ch.islower():
cnt_lcase+=1
if ch.isupper():
cnt_ucase+=1
if ch.isdigit():
cnt_digits+=1
print("Total Number of Upper Case letters are:",cnt_ucase)
print("Total Number of Lower Case letters are:",cnt_lcase)
print("Total Number of digits are:",cnt_digits)
filecreation()
operation()
OUTPUT :
Type a para maximum 2 lines :A package is a container that contains Various 1234
Total Number of Upper Case letters are: 2
Total Number of Lower Case letters are: 37
Total Number of digits are: 4
EXNO:12.1
Exception Handling Program using Zero division Error
PROGRAM:
try:
x=int(input("Enter the first value :"))
y=int(input("Enter the second value:"))
z=x/y
except ZeroDivisionError:
print("ZeroDivisionError Block")
print("Division by zero is not allowed ")
else:
print("Division of x and y is :",z)
OUTPUT:1
Enter the first value :6
Enter the second value:9
Division of x and y is : 0.6666666666666666
OUTPUT:2
Enter the first value :24
Enter the second value:0
ZeroDivisionError Block
Division by zero is not allowed
EXNO:12.2
TO FIND THE GIVEN AGE IS ELIGIBLE FOR VOTE OR NOT USING
RAISE KEYWORD
PROGRAM:
try:
x=int(input("Enter your age :"))
if x>100 or x<0:
raise ValueError
except ValueError:
print(x,"is not a valid age! Try again")
else:
if x>17:
print(x,"is eligible for vote")
else:
print(x,"is not eligible for vote")
OUTPUT :1
Enter your age :6
6 is not eligible for vote
OUTPUT:2
Enter your age :1999
1999 is not a valid age! Try again
OUTPUT :3
Enter your age :24
24 is eligible for vote
EXNO:12.3
Multiple Exception Handling
PROGRAM:
try:
a=int(input("Enter the first number :"))
b=int(input("Enter the second number :"))
print ("Division of a", a,"& b",b, "is : ", a/b)
except (TypeError,ValueError):
print('Unsupported operation')
except ZeroDivisionError:
print ('Division by zero not allowed')
else:
print ('End of No Error')
OUTPUT 1:
Enter the first number :5
Enter the second number :4
Division of a 5 & b 4 is : 1.25
End of No Error
OUTPUT 2:
Enter the first number :4
Enter the second number :r
Unsupported operation
EX.NO:13.1
TO DISPLAY THE DETAILS USING CLASS
PROGRAM:
class Student:
def getStudentInfo(self):
self.rollno=input("Roll Number: ")
self.name=input("Name: ")
def PutStudent(self):
print("Roll Number : ", self.rollno,"Name : ", self.name)
class Bsc(Student):
def GetBsc(self):
self.getStudentInfo()
self.p=int(input("Physics Marks: "))
self.c = int(input("Chemistry Marks: "))
self.m = int(input("Maths Marks: "))
def PutBsc(self):
self.PutStudent()
print("Marks is Subjects ", self.p,self.c,self.m)
class Ba(Student):
def GetBa(self):
self.getStudentInfo()
self.h = int(input("History Marks: "))
self.g = int(input("Geography Marks: "))
self.e = int(input("Economic Marks: "))
def PutBa(self):
self.PutStudent()
print("Marks is Subjects ", self.h,self.g,self.e)
print("Enter Bsc Student's details")
student1=Bsc()
student1.GetBsc()
student1.PutBsc()
print("Enter Ba Student's details")
student2=Ba()
student2.GetBa()
student2.PutBa()
OUTPUT:
Enter Bsc Student's details
Roll Number: 4575
Name: sakthi
Physics Marks: 87
Chemistry Marks: 67
Maths Marks: 66
Roll Number : 4575 Name : sakthi
Marks is Subjects 87 67 66
Enter Ba Student's details
Roll Number: 123
Name: siva
History Marks: 78
Geography Marks: 89
Economic Marks: 99
Roll Number : 123 Name : siva
Marks is Subjects 78 89 99