0% found this document useful (0 votes)
22 views63 pages

sakthi_py_lab1[1]

The document outlines a comprehensive Python programming laboratory curriculum, detailing various experiments and exercises. It covers fundamental programming concepts such as variable manipulation, conditional statements, loops, searching algorithms, sorting algorithms, and data structures like lists, tuples, sets, and dictionaries. Additionally, it includes practical applications using libraries and file handling, as well as exception handling and class creation.

Uploaded by

Sakthi Vel
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)
22 views63 pages

sakthi_py_lab1[1]

The document outlines a comprehensive Python programming laboratory curriculum, detailing various experiments and exercises. It covers fundamental programming concepts such as variable manipulation, conditional statements, loops, searching algorithms, sorting algorithms, and data structures like lists, tuples, sets, and dictionaries. Additionally, it includes practical applications using libraries and file handling, as well as exception handling and class creation.

Uploaded by

Sakthi Vel
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/ 63

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("\t\tExchange 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:20

Enter a value of y:40

Before Swapping :

The value of x : 20 and y : 40

After Swapping :

The value of x : 40 and y : 20


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

Enter a value of y:300

Before Swapping :

The value of x : 200 and y : 300

After Swapping :

The value of x : 300 and y : 200


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

Enter x2 value :4

Enter y1 value :6

Enter y2 value :8

Distance Between Two Point is : 2.8284271247461903


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

2 is Even number

Output 2:

TO FIND ODD OR EVEN NUMBER IN PYTHON

Enter a number: 77

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

Enter the 2nd number :200

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

Enter m2 mark :98

Enter m3 mark :67

Enter m4 mark :90

Enter m5 mark :77

Total : 410

Average : 82.0

Pass

1st class Distinction


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

675 is not a Armstrong number


EX.NO:2.5

TO FIND THE FACTORIAL OF GIVEN NUMBER


Program:

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

array=[6,9,12,11,24,99]

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 a number to find : 99

Element found at index: 5

Output :2

Enter a number to find : 55

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 = [6,9,11,24,99,100]

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 a Elements to find : 24

Element is present at index 3

Output :2

Enter a Elements to find : 80

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

24

11

29

Before sorted list: [24, 11, 9, 6, 29, 7]

After sorted list using selection sort: [7, 6, 9, 11, 24, 29]
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

11

24

99

Before sorted array: [11, 24, 6, 9, 99, 1]

After sorted array using insertion sort : [1, 6, 9, 11, 24, 99]
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

24

11

99

Before sorted array : [24, 11, 6, 9, 1, 99]

Sorted array using merge sort: [1, 6, 9, 11, 24, 99]


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

24

11

99

Before sorted list: [24, 6, 11, 9, 1, 99]

Sorted Array using quicksort: [1, 6, 9, 11, 24, 99]


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

list1=[10,20,30,40,50]

print("Before Appending ",list1)

list1.append(60)

print("After Appending ",list1)

list2=[100,200,300,400,500]

print("Before Reverse ",list2)

list2.reverse()

print("After reverse ",list2)

list3=[10,20,30,40,50]

print("Before pop in list ",list3)

list3.pop(1)

print("After pop in List ",list3)

Output:

To Find Append , Reverse And Pop In a List

Before Appending [10, 20, 30, 40, 50]

After Appending [10, 20, 30, 40, 50, 60]

Before Reverse [100, 200, 300, 400, 500]

After reverse [500, 400, 300, 200, 100]

Before pop in list [10, 20, 30, 40, 50]

After pop in List [10, 30, 40, 50]


EX.NO: 6.2

PROGRAM FOR SLICING LIST


PROGRAM:

print("Program For Slicing List")

print()

a=[1,2,3,4,5,6,7,8,9,10]

print("list A ",a )

print("Index 0 to 3 :",a[0:4])

print("Index 3 to 5 :",a[3:6])

print("Last Element in List :",a[-1])

Output :

Program For Slicing List

list A [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Index 0 to 3 : [1, 2, 3, 4]

Index 3 to 5 : [4, 5, 6]

Last Element in List : 10

Reverse a List : [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]


EX.NO: 6.3

TO DISPLAY THE MAXIMUM AND MINIMUM VALUE IN


THE TUPLE
PROGRAM:

print("To Display The Maximum And Minimum\n")

a=(10,20,30,40,50,60)

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

Tuple is (10, 20, 30, 40, 50, 60)

Highest value is 60

Lowest value is 10
EXNO:6.4

To interchange two values using tuple assignment


Program :

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

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

print("Before swap tuple Value of A = ",a,"\n Value of B = " , b)

(a, b) = (b, a)

print("After swap tuple Value of A = ", a,"\n Value of B = ", b)

Output :

Enter value of A: 24

Enter value of B: 6

Before swap tuple Value of A = 24

Value of B = 6

After swap tuple Value of A = 6

Value of B = 24
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")

a={5,10,15,20,25,30}

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

sum_set=sum(a)

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

b={1,2,3,4,5}

print("Before Adding b set ",b)

b.add(6)

print("After Adding b Set ",b)

c={10,20,30,40,50}

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

c.remove(10)

print("After Remove Element in set ",c)

Output:

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

Set a value is : {20, 5, 25, 10, 30, 15}

Sum of Element In Set : 105

Before Adding b set {1, 2, 3, 4, 5}

After Adding b Set {1, 2, 3, 4, 5, 6}

Before Remove Element in Set {50, 20, 40, 10, 30}

After Remove Element in set {50, 20, 40, 30}


EX.NO: 7.2

TO DISPLAY INTERSECTION OF ELEMENT AND


DIFFERENCE OF ELEMENT IN THE SET
PROGRAM:

a={1,2,3,4,5}

b={5,6,7,2,1}

print("A set is ",a)

print("B set is ",b)

print("Intersection of sets ",a.intersection(b))

print("Difference of sets 'a' & 'b' ",a.difference(b))

Output:

To Display Intersection Of Element And Different Of Element In The Set

A set is {1, 2, 3, 4, 5}

B set is {1, 2, 5, 6, 7}

Intersection of sets {1, 2, 5}

Difference of sets 'a' & 'b' {3, 4}


EXNO:7.3

TO UPDATING A ELEMENTS IN A DICTONARY


PROGRAM:

Dictionary1 = {'A': 'PTYHON', 'B': 'PROGRAM', }

Dictionary2 = {'B': 'EASY'}

print("Original Dictionary:")

print(Dictionary1)

Dictionary1.update(Dictionary2)

print("Dictionary after updation:")

print(Dictionary1)

OUTPUT:

Original Dictionary:

{'A': 'PTYHON', 'B': 'PROGRAM'}

Dictionary after updation:

{'A': 'PTYHON', 'B': 'EASY'}


EXNO:7.4

SUM OF ALL ITEMS IN A DICTIONARY

Program :

def returnSum(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={'a': 200, 'b':800,'c':700}

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 :

Dictionary : {'a': 200, 'b': 800, 'c': 700}

Sum in method 1 : 1700

Sum in method 2 : 1700

Sum in method 3 : 1700


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 :

def GCD_Loop( ):

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

Enter the second number: 36

GCD of two number is: 12


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:

Enter a letter:csc

The given string is a palindrome

Enter a letter:python

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=np.arange(4,dtype=np.float_).reshape(2,2)

print('First array:')

print(arr1)

print("\nSecond array:")

arr2=np.array([12,12])

print(arr2)

print("\nAdding the two arrays:")

print(np.add(arr1,arr2))

print("\nSubtracting the two arrays:")

print(np.subtract(arr1,arr2))

print('\nMultiplying the two arrays:')

print(np.multiply(arr1,arr2))

print('\nDividing the two arrays:')

print(np.divide(arr1,arr2))
Output:

First array:

[[0. 1.]

[2. 3.]]

Second array:

[12 12]

Adding the two arrays:

[[12. 13.]

[14. 15.]]

Subtracting the two arrays:

[[-12. -11.]

[-10. -9.]]

Multiplying the two arrays:

[[ 0. 12.]

[24. 36.]]

Dividing the two arrays:

[[0. 0.08333333]

[0.16666667 0.25 ]]
EX.NO:10.2

Dataframe From Three Series Using Pandas


Program:

import pandas as pd

employees = pd.DataFrame({

'EmpCode': ['Emp001', 'Emp002', 'Emp003', 'Emp004', 'Emp005'],

'Name': ['John', 'Doe', 'William', 'Spark', 'Mark'],

'Occupation': ['Chemist', 'Statistician', 'Statistician',

'Statistician', 'Programmer'],

'Date Of Join': ['2018-01-25', '2018-01-26', '2018-01-26', '2018-02-26',

'2018-03-16'],

'Age': [23, 24, 34, 29, 40]})

print("Employees Record")

print(employees)

employees['City'] = ['London', 'Tokyo', 'Sydney', 'London', 'Toronto']

print("Employees Record After Adding Coloumn")

print(employees)
print("\n Drop Column by Name \n")

employees.drop('Age', axis=1, inplace=True)

print("Employees Record After Dropping Coloumn by name")

print(employees)

print("\n Drop Column by Index \n")

employees.drop(employees.columns[[0,1]], axis=1, inplace=True)

print("Employees Record After Dropping Coloumn by index")

print(employees)

print("\n Update Programmer as Soft. Engg \n")

employees.loc[employees.Occupation=='Programmer','Occupation']='S/W Engg'

print("Employees Record After Update")

print(employees)

employees.insert(3,"Country","US")

print("Employees Record After Insert")

print(employees)
OUTPUT:

Employees Record

EmpCode Name Occupation Date Of Join Age

0 Emp001 John Chemist 2018-01-25 23

1 Emp002 Doe Statistician 2018-01-26 24

2 Emp003 William Statistician 2018-01-26 34

3 Emp004 Spark Statistician 2018-02-26 29

4 Emp005 Mark Programmer 2018-03-16 40

Employees Record After Adding Coloumn

EmpCode Name Occupation Date Of Join Age City

0 Emp001 John Chemist 2018-01-25 23 London

1 Emp002 Doe Statistician 2018-01-26 24 Tokyo

2 Emp003 William Statistician 2018-01-26 34 Sydney

3 Emp004 Spark Statistician 2018-02-26 29 London

4 Emp005 Mark Programmer 2018-03-16 40 Toronto

Drop Column by Name

Employees Record After Dropping Coloumn by name


EmpCode Name Occupation Date Of Join City

0 Emp001 John Chemist 2018-01-25 London

1 Emp002 Doe Statistician 2018-01-26 Tokyo

2 Emp003 William Statistician 2018-01-26 Sydney

3 Emp004 Spark Statistician 2018-02-26 London

4 Emp005 Mark Programmer 2018-03-16 Toronto

Drop Column by Index

Employees Record After Dropping Coloumn by index

Occupation Date Of Join City

0 Chemist 2018-01-25 London

1 Statistician 2018-01-26 Tokyo

2 Statistician 2018-01-26 Sydney

3 Statistician 2018-02-26 London

4 Programmer 2018-03-16 Toronto

Update Programmer as Soft. Engg


Employees Record After Update

Occupation Date Of Join City

0 Chemist 2018-01-25 London

1 Statistician 2018-01-26 Tokyo

2 Statistician 2018-01-26 Sydney

3 Statistician 2018-02-26 London

4 S/W Engg 2018-03-16 Toronto

Employees Record After Insert

Occupation Date Of Join City Country

0 Chemist 2018-01-25 London US

1 Statistician 2018-01-26 Tokyo US

2 Statistician 2018-01-26 Sydney US

3 Statistician 2018-02-26 London US

4 S/W Engg 2018-03-16 Toronto US


EX.NO:10.3

PROGRAM TO LINE CHART-MATPLOTLIB

Program:

from matplotlib import pyplot as plt

from matplotlib import style

style.use('ggplot')

x=[5,8,10]

y=[12,16,6]

x2=[6,9,11]

y2=[6,15,7]

plt.plot(x,y,'b',label='line one',linewidth=6)

plt.plot(x2,y2,'r',label='line two',linewidth=9)

plt.title('Epic Info')

plt.ylabel('y axis')

plt.xlabel('x axis')

plt.legend()

plt.grid(True,color='k')

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

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 : Python is a general purpose programming language created by

Guido Van Rossum .It was released in 1991.

Writing File1 Succussful

Enter the para for Java file :Java also a progammin language created by Sun Microsystems .

Java was released in1990's

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 programming -Mc4102

Total Number of Upper Case letters are: 2

Total Number of Lower Case letters are: 17

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:

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

Enter the second number :0

Division by zero not allowed

Enter the first number :6

Enter the second number :'6'

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

You might also like