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

parthi.py_lab[1]

The document outlines a Python programming laboratory course, detailing various experiments and exercises related to programming concepts such as variable manipulation, conditional statements, loops, search algorithms, sorting algorithms, and data structures. Each section includes specific tasks to be completed, such as exchanging variable values, finding prime numbers, and implementing sorting algorithms. Additionally, the document provides example codes and outputs for practical understanding.

Uploaded by

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

parthi.py_lab[1]

The document outlines a Python programming laboratory course, detailing various experiments and exercises related to programming concepts such as variable manipulation, conditional statements, loops, search algorithms, sorting algorithms, and data structures. Each section includes specific tasks to be completed, such as exchanging variable values, finding prime numbers, and implementing sorting algorithms. Additionally, the document provides example codes and outputs for practical understanding.

Uploaded by

Sakthi Vel
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 77

INDEX

MC4112 - Python Programming Laboratory

EXP. DATE EXPERIMENT PAG SIGN


NO E
NO.
PYTHON PROGRAMMING USING SIMPLE STATEMENT AND EXPRESSIONS

(TO FIND THE ABSOLUTE VALUE,EXCHANGE THE VALUES OF TWO


VARIABLES WITHOUT TEMPORARY VARIABLE, , DISTANCE BETWEEN
TWO POINT,TO FIND SQUARE ROOT OF A NUMBER).

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 variable

1. SCIENTIFIC PROBLEM USING CONDITIONAL AND ITERATIVE LOOPS.

2.1 To covert binary to decimal

2.2 To find biggest among three number

2.3 To print 1 to 50 prime number

2.4 To find given number is armstrong number or not


using while loop

2.5 To find the given number is positive or negative or


zero

2.6 To find the greatest common divisor of two number

2. LINEAR SEARCH AND BINARY SEARCH

3.1 Linear Search

3.2 Binary Search


3. SELECTION SORT AND INSERTION SORT

4.1 Selection sort

4.2 Insertion sort

4. MERGE SORT AND QUICK SORT

5.1 Merge sort

5.2 Quick sort

5. 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

6. 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

7. 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
8. 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

9. 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("\t\tExchange the values of two variables with 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)

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 variable

Enter a value of x:120

Enter a value of y:200

Before Swapping :

The value of x : 120 and y : 200

After Swapping :

The value of x : 200 and y : 120


EXNO:1.2

EXCHANGE THE VALUES OF TWO VARIABLES WITHOUT


TEMPORARY VARIABLE

PROGRAM:

print("\t\t 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:123

Enter a value of y:456

Before Swapping :

The value of x : 123 and y : 456

After Swapping :

The value of x : 456 and y : 123


EXNO:1.3

Calculate Distance between two points


Program :

import math

print("\t\tCalculating 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 :16

Enter x2 value :22

Enter y1 value :44

Enter y2 value :28

Distance Between Two Point is : 17.08800749063506


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:3

Enter integer:12

Enter integer:13

Enter integer:14

Circulating the elements of list: [12, 13, 14]

[13, 14, 12]

[14, 12, 13]

[12, 13, 14]


EXNO:2.1

TO CONVERT BINARY TO DECIMAL


PROGRAM:

n=int(input("Enter a binary number :"))

m=n

s=0

x=0

while(n>0):

i=n%10

x=x+i*pow(2,s)

s=s+1

n=n//10

print("decimal of binary",m,"is",x)

Output :

Enter a binary number :11011

decimal of binary 11011 is 27


EXNO:2.2

TO FIND BIGGEST AMONG THREE NUMBERS


PROGRAM:

print("\t\tTO FIND BIGGEST AMONG 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 AMONG THREE NUMBERS

Enter the 1st number :143

Enter the 2nd number :687

Enter the 3rd number :127

687 is largest

EX.NO: 2.3
TO PRINT 1 TO 50 PRIME NUMBER

Program:

print("\t\tTo print 1 to 50 prime number")

start=int(input("Enter the start value :"))

end=int(input("Enter the end value :"))

for num in range(start,end+1):

if num>1:

for i in range(2,num):

if(num%i)==0:

break

else:

print("prime number",start,"to",end,"is",num)

Output:

To print 1 to 50 prime number

Enter the start value :1

Enter the end value :50

prime number 1 to 50 is 2

prime number 1 to 50 is 3

prime number 1 to 50 is 5

prime number 1 to 50 is 7

prime number 1 to 50 is 11

prime number 1 to 50 is 13

prime number 1 to 50 is 17

prime number 1 to 50 is 19
prime number 1 to 50 is 23

prime number 1 to 50 is 29

prime number 1 to 50 is 31

prime number 1 to 50 is 37

prime number 1 to 50 is 41

prime number 1 to 50 is 43

prime number 1 to 50 is 47

EXNO:2.4
TO FIND A AMSTRONG NUMBER

PROGRAM:

print("\t\tTO 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: 153

153 is a Armstrong number

Output 2:

TO FIND A AMSTRONG NUMBER

Enter a number: 120

120 is not a Armstrong number

EX.NO:2.5
TO FIND THE GIVEN NUMBER IS POSITIVE OR NEGATIVE OR
ZERO
Program:

print("\t\tFinding given number is positive or negative or zero")

n=int(input("Enter your number :"))

if n>0:

print(n,"posiive value")

elif n<0:

print(n,"negative value")

else:

print(n,"is zero")

Output 1:

Finding given number is positive or negative or zero

Enter your number :6

6 positive value

Output 2:

Finding given number is positive or negative or zero

Enter your number :-3

-3 negative value

Output 3:

Finding given number is positive or negative or zero

Enter your number :0

0 is zero

EXNO:2.6
TO FIND THE GREATEST COMMON DIVISOR OF TWO
NUMBER

PROGRAM:

print("\t\tfind the GCD of two number")

a=int(input("Enter A value :"))

b=int(input("Enter B value :"))

def hcf(a, b):

if(b == 0):

return a

else:

return hcf(b, a % b)

print("the Greatest Common Divisor of two number ",a,"and",b,"is",hcf(a,b))

OUTPUT:

find the GCD of two number

Enter A value :12

Enter B value :6

the Greatest Common Divisor of two number 12 and 6 is 6

EXNO:3.1
LINEAR SEARCH
Program :

def linearSearch(array, n, x):

for i in range(0, n):

if(array[i]==x):

return i

return -1

array=[]

a=int(input("Enter limit :"))

for i in range(1,a+1):

n=int(input("Enter value :"))

array.append(n)

x=int(input("Enter a number to find : "))

n=len(array)

result = linearSearch(array, n, x)

if(result == -1):

print("Element not found",result)

else:

print("Element found at index:",result)

Output :1
Enter limit :5

Enter value :12

Enter value :56

Enter value :90

Enter value :67

Enter value :43

Enter a number to find : 56

Element found at index: 1

Output :2

Enter limit :3

Enter value :24

Enter value :98

Enter value :54

Enter a number to find : 33

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 = []

a=int(input("Enter limit :"))

for i in range(1,a+1):

n=int(input("Enter value :"))

list1.append(n)

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 limit :5

Enter value :12

Enter value :34

Enter value :56

Enter value :67

Enter value :888

Enter a Elements to find : 67

Element is present at index 3

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: 5

87

65

93

23

61

Before sorted list: [87, 65, 93, 23, 61]

After sorted list using selection sort: [61, 23, 65, 87, 93]

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

678

234

668

234

800

345

Before sorted array: [678, 234, 668, 234, 800, 345]

After sorted array using insertion sort : [234, 234, 345, 668, 678, 800]

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()

if __name__ == '__main__':

array = []

p=int(input("Number of elements: "))

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: 6

78

45

23

89

71

34

Before sorted array : [78, 45, 23, 89, 71, 34]

Sorted array using merge sort: [23, 34, 45, 71, 78, 89]

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: 5

93

45

72

61

40

Before sorted list: [93, 45, 72, 61, 40]

Sorted Array using quicksort: [40, 45, 61, 72, 93]


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\tAppend a list")

a=int(input("Enter how many value :"))

list1=[]

print("Enter list elemenet :")

for i in range(1,a+1):

l=int(input())

list1.append(l)

print("Before Appending ",list1)

n=int(input("Enter the elements :"))

list1.append(n)

print("After Appending ",list1)

print()

print("\t\tReverse a list")

list2=[]

a=int(input("Enter how many value :"))

print("Enter list elemenet :")

for i in range(1,a+1):

l=int(input())

list2.append(l)

print("Before Reverse ",list2)

n=int(input("Enter the elements :"))


list2.reverse()

print("After reverse ",list2)

print()

print("\t\tPop a list")

a=int(input("Enter how many value :"))

list3=[]

print("Enter list elemenet :")

for i in range(1,a+1):

l=int(input())

list3.append(l)

print("Before pop in list ",list3)

n=int(input("Enter the elements :"))

list3.pop(1)

print("After pop in List ",list3)

print()
Output:

To Find Append , Reverse And Pop In a List

Append a list

Enter how many value :3

Enter list elemenet :

89

54

12

Before Appending [89, 54, 12]

Enter the elements :55

After Appending [89, 54, 12, 55]

Reverse a list

Enter how many value :3

Enter list elemenet :

56

30

81

Before Reverse [56, 30, 81]

Enter the elements :21

After reverse [81, 30, 56]

Pop a list

Enter how many value :3

Enter list elemenet :

82

71
17

Before pop in list [82, 71, 17]

Enter the elements :71

After pop in List [82, 17]

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):

p=int(input())

list1.append(p)

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 :7

Enter List Element :

68

78

65

39

13

29

87

list is [68, 78, 65, 39, 13, 29, 87]

Index 0 to 3 : [68, 78, 65, 39]

Index 3 to 5 : [39, 13, 29]

Index To print Reverse : [87, 29, 13, 39, 65, 78, 68]

Last Element in List : 87

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):

q=int(input())

list1.append(q)

r=tuple(list1)

print("Tuple is ",r)

highest=max(r)

print("Maximum value is ",highest)

low=min(r)

print("Minimum value is ",low)

Output :
To Display The Maximum And Minimum

Enter how Many Value :5

Enter List Element :

78

124

92

11

Tuple is (78, 3, 124, 92, 11)

Maximum value is 124

Minimum value is 3

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: 99

Enter value of B: 77

Before swap tuple Value of A = 99 Value of B = 77

After swap tuple Value of A = 77 Value of B = 99


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):

m=int(input())

list1.append(m)

v=set(list1)

print()

print("Set a value is :",v)

sum_set=sum(v)

print("Sum of Element In Set :",sum_set)

print()

print("Before Adding set ",v)

print("Enter Adding Element :")

p=int(input())

v.add(p)

print("After Adding Set ",v)

print()

print("Before Remove Element in Set ",v)

print("Enter Remove Element :")

p=int(input())

v.remove(p)
print("After Remove Element in set ",v)

Output:

To Display Sum Of Element , Add Element And Remove Element In The Set

Enter how Many Value :5

Enter List Element :

11

12

13

14

15

Set a value is : {11, 12, 13, 14, 15}

Sum of Element In Set : 65

Before Adding set {11, 12, 13, 14, 15}

Enter Adding Element :

16

After Adding Set {11, 12, 13, 14, 15, 16}

Before Remove Element in Set {11, 12, 13, 14, 15, 16}

Enter Remove Element :

14

After Remove Element in set {11, 12, 13, 15, 16}

EX.NO: 7.2
TO DISPLAY INTERSECTION OF ELEMENT AND
DIFFERENCE OF ELEMENT IN THE SET
PROGRAM:

x=int(input("Enter how Many Value :"))

list1=[]

print("Enter Set A Element :")

for i in range(1,x+1):

y=int(input())

list1.append(y)

c1=set(list1)

x=int(input("Enter how Many Value For B set :"))

list2=[]

print("Enter Set B Element :")

for i in range(1,x+1):

y=int(input())

list2.append(y)

d1=set(list2)

print("C set is ",c1)

print("D set is ",d1)

print("Intersection of sets ",c1.intersection(d1))

print("Difference of sets 'c1' & 'd1' ",c1.difference(d1))

Output:
Enter how Many Value :4

Enter Set A Element :

11

22

33

44

Enter how Many Value For B set :4

Enter Set B Element :

33

44

55

66

C set is {33, 11, 44, 22}

D set is {33, 66, 44, 55}

Intersection of sets {33, 44}

Difference of sets 'c1' & 'd1' {11, 22}

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 :")

age=input("Enter age :")

Dictionary1[name]=age

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 :")

age=input("Enter salary :")

Dictionary2[name]=age

Dictionary1.update(Dictionary2)

print("Dictionary after updation:")

print(Dictionary1)
OUTPUT:

Dictionary 1

Enter How many value :2

Enter Name :king

Enter age :45

Enter Name :queen

Enter age :35

Original Dictionary:

{'king': '45', 'queen': '35'}

Dictionary 2

Enter How many value :1

Enter Name :jack

Enter salary :30

Dictionary after updation:

{'king': '45', 'queen': '35', 'jack': '30'}

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 :x

Enter values :111

Enter keys :y

Enter values :222

Enter keys :z

Enter values :333

Dictionary : {'x': 111, 'y': 222, 'z': 333}

Sum in method 1 : 666

Sum in method 2 : 666

Sum in method 3 : 666

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):

solution=(h*b)/2

return solution

a=int(input("Enter height :"))

b=int(input("Enter base :"))

solution=area_triangle(a,b)

print("Area Of Triangle is ",solution)

Output :

Calculate The Area Of A Triangle Using

With Argument With return type

Enter height :15

Enter base :7

Area Of Triangle is 52.5

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

number = GCD_Loop()

print("GCD of two number is: ",number)

Output :
To Greatest commom Divisor

Using

with Argument Without Return Type Function

Enter the first number: 96

Enter the second number: 57

GCD of two number is: 3

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 1 :

To Factorial Of Given Number Using Regreression

Enter a number:6

The factorial of 6 is 720

OUTPUT 2:

To Factorial Of Given Number Using Regreression

Enter a number:-3

sorry,factorial does not exist for negative numbers

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 : master of computer application

The number of vowels: 11

The number of consonant: 19

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:

Enter a letter:dad

The given string is a palindrome

Enter a letter:father

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 :"))

name=[]

for i in range(n):

a=input("Enter Name :")

name.append(a)

print("Before Sorting ",name)

name.sort()

print("After Sorting ",name)

Output:

To Read N Name And Sort Name In Alphabetic Order Using String

ENTER A HOW MANY VALUE :3

Enter Name :append

Enter Name :coding

Enter Name :block of statement

Before Sorting ['append', 'coding', 'block of statement']

After Sorting ['append', 'block of statement', 'coding']

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 First Array

Enter How Many Row :2

Enter How Many Coloum :2

Enter Element :1

Enter Element :4

Enter Element :2

Enter Element :7

[[1 4]

[1 4]

[2 7]

[2 7]]

Enter Second Array

Enter How Many Row :2

Enter How Many Coloum :2

Enter Element :12

Enter Element :4

Enter Element :5

Enter Element :11

Second array:

[[12 4]

[12 4]

[ 5 11]

[ 5 11]]

Adding the two arrays:

[[13 8]
[13 8]

[ 7 18]

[ 7 18]]

Subtracting the two arrays:

[[-11 0]

[-11 0]

[ -3 -4]

[ -3 -4]]

Multiplying the two arrays:

[[12 16]

[12 16]

[10 77]

[10 77]]

Dividing the two arrays:

[[0.08333333 1. ]

[0.08333333 1. ]

[0.4 0.63636364]

[0.4 0.63636364]]
EX.NO:10.2

Dataframe From Three Series Using Pandas


Program:

import pandas as pd

print("Display Scorecard Pandas")

pla = {'Jersy_no':[],'Name':[],'Balls':[],'Run':[],'Strikerate':[]}

while True:

print("\t\tMenu Card\n")

print("1) Adding players Details ")

print("2) Display Players Details")

print("3) Insert New feature on board ")

print("4) Drop Coloumn By Name ")

print("5) Exit")

c=int(input("Enter Your Choise :"))

if c==1:

no=int(input("Enter No.Of players :"))

for i in range(no):

Jersey_no=int(input("Enter Jersy no :"))

Name=input("Enter Name :")

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


Run=input("Enter Run :")

Strikerate=input("Enter strikerate :")

pla['Jersy_no'].append(Jersey_no)

pla['Name'].append(Name)

pla['Balls'].append(Balls)

pla['Run'].append(Run)

pla['Strikerate'].append(Strikerate)

pla = pd.DataFrame(pla)

elif c==2:

print(pla)

elif c==3:

print("Adding new feature on board")

x=int(input("Enter Numer of team :"))

team = []

for i in range(x):

P = input("Enter team name : ")

team.append(P)

pla['Team'] = team

print("After Insert New feaures")

print(pla)
elif c==4:

print("Drop Coloumn By Name")

n=input("Enter Drop coloumn Name With correct Spelling :")

pla.drop(str(n), axis=1, inplace=True)

print(pla)

elif c==5:

break

print("Thank you for watching our program !!")

OUTPUT:
Display Scorecard Pandas

Menu Card

1) Adding players Details

2) Display Players Details

3) Insert New feature on board

4) Drop Coloumn By Name

5) Exit

Enter Your Choise :1

Enter No.Of players :2

Enter Jersy no :18

Enter Name :virat

Enter Balls :20

Enter Run :42

Enter strikerate :210.00

Enter Jersy no :45

Enter Name :rohit

Enter Balls :33

Enter Run :56

Enter strikerate :175.5


Menu Card

1) Adding players Details

2) Display Players Details

3) Insert New feature on board

4) Drop Coloumn By Name

5) Exit

Enter Your Choise :2

Jersy_no Name Balls Run Strikerate

0 18 virat 20 42 210.00

1 45 rohit 33 56 175.5

Menu Card

1) Adding players Details

2) Display Players Details

3) Insert New feature on board

4) Drop Coloumn By Name

5) Exit

Enter Your Choise :3

Adding new feature on board


Enter Numer of team :2

Enter team name : RCB

Enter team name : MI

After Insert New feaures

Jersy_no Name Balls Run Strikerate Team

0 18 virat 20 42 210.00 RCB

1 45 rohit 33 56 175.5 MI

Menu Card

1) Adding players Details

2) Display Players Details

3) Insert New feature on board

4) Drop Coloumn By Name

5) Exit

Enter Your Choise :4

Drop Coloumn By Name

Enter Drop coloumn Name With correct Spelling :Balls

Jersy_no Name Run Strikerate Team

0 18 virat 42 210.00 RCB

1 45 rohit 56 175.5 MI
Menu Card

1) Adding players Details

2) Display Players Details

3) Insert New feature on board

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:
EX.NO:11.4

PROGRAM TO USING SCIPY

PROGRAM:

from scipy import misc

from matplotlib import pyplot as plt

import numpy as np

panda= misc.face()

plt.imshow(panda)

plt.show()

flip_down = np.flipud(misc.face())

plt.imshow(flip_down)

plt.show()
OUTPUT:
EXNO:11.1

Merging two files


Program :

def program1():

f = open("python2.txt","w")

p=input("Enter the para for python file :")

freshline="\n"

f.write(p)

f.write(freshline)

f.close()

def program2():

f = open("Javafile.txt","w")

p=input("Enter the para for Java file :")

freshline="\n"

f.write(p)

f.write(freshline)

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 python file :import numpy as np

Writing File1 Succussful

Enter the para for Java file :int main()

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 :Python is a sensitive language and it is founded by Guido van Rossum
on feb 20 1991

Total Number of Upper Case letters are: 3

Total Number of Lower Case letters are: 58

Total Number of digits are: 6


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 :12

Enter the second value:6

Division of x and y is : 2.0

Output:2

Enter the first value :33

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 :21

21 is eligible for vote

Output:2

Enter your age :16

16 is not eligible for voteOutput :3

Output:3

Enter your age :2002

2002 is not a valid age! Try again


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:

print('Unsupported operation')

except ZeroDivisionError:

print ('Division by zero not allowed')

else:

print ('End of No Error')

try:

a=int(input("Enter the first number :"))

b=int(input("Enter the second number :"))

print (a/b)

except ValueError:

print('Unsupported operation')

except ZeroDivisionError:

print ('Division by zero not allowed')


Output:
Enter the first number :12

Enter the second number :77

Division of a 12 & b 77 is : 0.15584415584415584

End of No Error

Enter the first number :11

Enter the second number :0

Division by zero not allowed


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: 111

Name: seran

Physics Marks: 8

Chemistry Marks: 78

Maths Marks: 92

Roll Number : 111 Name : seran

Marks is Subjects 8 78 92

Enter Ba Student's details

Roll Number: 112

Name: cholan

History Marks: 99

Geography Marks: 43

Economic Marks: 78

Roll Number : 112 Name : cholan

Marks is Subjects 99 43 78

You might also like