[go: up one dir, main page]

0% found this document useful (0 votes)
24 views25 pages

Pylab Manual

For BCA 3rd Sem python programming subject lab programs

Uploaded by

meghanaraj7776
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views25 pages

Pylab Manual

For BCA 3rd Sem python programming subject lab programs

Uploaded by

meghanaraj7776
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Python lab manual 2023-24

LAB MANUAL 2023-


24

CA-C15L: PYTHON
PROGRAMMING LAB
III SEM BCA

ST. CLARET COLLEGE

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

DEPARTMENT OF COMPUTER SCIENCE.

1. Write a program to demonstrate basic data type in python.


a=10
b="Python"
c = 10.5
d=2.14j
e=True
print("Data type of Variable a :",type(a))
print("Data type of Variable b :",type(b))
print("Data type of Variable c :",type(c))
print("Data type of Variable d :",type(d))
print("Data type of Variable e :",type(e))

Output:
Data type of Variable a : <class 'int'>
Data type of Variable b : <class 'str'>
Data type of Variable c : <class 'float'>
Data type of Variable d : <class 'complex'>
Data type of Variable e : <class 'bool'>

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

2. Create a list and perform the following methods


1) insert() 2) remove() 3) append()
4) len() 5) pop() 6) clear()

a=[1,3,5,6,7,4,"hello"]
print(a)
#insert()
a.insert(3,20)
print(a)
#remove()
a.remove(7)
print(a)
#append()
a.append("hi")
print(a)
c=len(a)
print(c)
#pop()
a.pop()
print(a)
a.pop(6)
print(a)
# clear()
a.clear()
print(a)

Output:

[1, 3, 5, 6, 7, 4, 'hello']
[1, 3, 5, 20, 6, 7, 4, 'hello']
[1, 3, 5, 20, 6, 4, 'hello']
[1, 3, 5, 20, 6, 4, 'hello', 'hi']
8
[1, 3, 5, 20, 6, 4, 'hello']
[1, 3, 5, 20, 6, 4]
[]

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

3. Create a tuple and perform the following methods.


1) add items 2) len() 3) check for item in tuple 4) Access items

#creating a tuple
rainbow=("v","i","b","g","y","o","r")
print(rainbow)
colour=("violet","blue","green","yellow","orange","red")
print(colour)

# Add items in tuples


rainbow_colour=rainbow+colour
print(rainbow_colour)

#length of the tuple


c=len(rainbow_colour)
print(c)

#check for item in tuple


if “i” in rainbow:
print(“item is present”)

#Access items in tuple


print("rainbow[2]:",rainbow[2])

"""rainbow[1:3] means all the items in rainbow tuple starting from an index value
of 1 up to an index value of 4"""
print("rainbow[1:3]",rainbow[1:3])
print("rainbow[0:4]",rainbow[0:4])

Output:

('v', 'i', 'b', 'g', 'y', 'o', 'r')


('violet', 'blue', 'green', 'yellow', 'orange', 'red')
('v', 'i', 'b', 'g', 'y', 'o', 'r', 'violet', 'blue', 'green', 'yellow', 'orange', 'red')
13
rainbow[2]: b
rainbow[1:3] ('i', 'b')
rainbow[0:4] ('v', 'i', 'b', 'g')

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

4. Create a dictionary and apply the following methods

1) print the dictionary items 2) access items 3) use get()


4) change values 5) use len()

#Source code:
# creating a dictionary
college={'name': "CLARET", 'code': "SCC",'pincode': 560013 }
print(college)
#adding items to dictionary
college["location"] = "MES ring road"
print(college)
#changing values of a key
college["location"] = "Jalahalli Village"
print(college)
#know the length using len()
print("length of college is:",len(college))
#Acess items
print("college['name']:",college['name'])
# use get ()
x=college.get('pincode')
print(x)
#to copy the same dictionary use copy()
mycollege= college.copy()
print(mycollege)
Output:

{'name': 'CLARET', 'code': 'SCC', 'pincode': 560013}


{'name': 'CLARET', 'code': 'SCC', 'pincode': 560013, 'location': 'MES ring road'}
{'name': 'CLARET', 'code': 'SCC', 'pincode': 560013, 'location': 'Jalahalli Village'}
length of college is: 4
college['name']: CLARET
560013
{'name': 'CLARET', 'code': 'SCC', 'pincode': 560013, 'location': 'Jalahalli Village'}

5. Write a program to create a menu with the following options


1. TO PERFORM ADDITION 2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION 4. TO PERFORM DIVISION

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

def add(n1,n2):
return n1+n2
def sub(n1,n2):
return n1-n2
def mul(n1,n2):
return n1*n2
def div(n1,n2):
return n1/n2
print("Welcome to the Arithmetic Program")
choice =1
while(choice!=0):
x = int(input(" Enter the first number\n"))
y = int(input(" Enter the second number\n"))
print("1. TO PERFORM ADDITION")
print("2. TO PERFORM SUBTRACTION")
print("3. TO PERFORM MULTIPLICATION")
print("4. TO PERFORM DIVISION")
print("0. To Exit")
choice = int(input("Enter your choice"))
if choice == 1:
print(x, "+" ,y ,"=" ,add(x,y))
elif choice == 2:
print(x, "-" ,y ,"=" ,sub(x,y))
elif choice == 3:
print(x, "*" ,y ,"=" ,mul(x,y))
elif choice == 4:
print(x, "/" ,y ,"=" ,div(x,y))
elif choice ==0:
print("Exit")
else: print("Invalid Choice")

Output:
Welcome to the Arithmetic Program
Enter the first number
5
Enter the second number
8
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice1
5 + 8 = 13
Enter the first number
5
Enter the second number
5
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice2
5-5=0
Enter the first number
2
Enter the second number
2
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice3
2*2=4
Enter the first number
6
Enter the second number
2
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice4
6 % 2 = 3.0
Enter the first number
4

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

Enter the second number


5
1. TO PERFORM ADDITION
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPLICATION
4. TO PERFORM DIVISION
0. To Exit
Enter your choice0
Exit

6. Write a python program to print a number is positive/negative using if-else

print("Program to print a number is Positive / Negative")


choice =1
while(choice!=0):

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

number=int(input("Enter a Number: "))


if number >0:
print("The Number",number,"is Positive")
else:
print("The Number",number, "is negative")
choice=int(input("Do you wish to continue 1/0: "))

Output:

Program to print a number is Positive / Negative


Enter a Number: 5
The Number 5 is Positive
Do you wish to continue 1/0: 1
Enter a Number: -4
The Number -4 is negative
Do you wish to continue 1/0: 0

7. Write a program for filter() to filter only even numbers from a given list

#syntax:filter(function,sequence)

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

L1=[1,6,4,9,7,0,8,3]

#function f() take a value and returns TRUE if remainder is zero

def f(X):
return X%2==0

M=list(filter(f,L1))
print("Original list: ",L1)
print("Filtered list: ",M)

Output:

Original list: [1, 6, 4, 9, 7, 0, 8, 3]


Filtered list: [6, 4, 0, 8]

8. Write a python program to print date, time for today and now

import datetime
a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

print(b)

Output:

2023-09-09 09:13:26.600974
2023-09-09 09:13:26.600974

9. Write a python program to add some days to your present date and print
the date added.

from datetime import timedelta


from datetime import date

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

# taking input as the current date


# today() method is supported by date
# class in datetime module
Begindatestring = date.today()

# print begin date print("Beginning date")


print(Begindatestring)

# calculating end date by adding days


days= int(input("how many days to add? "))
Enddate = Begindatestring + timedelta(days)

# printing end date print("Ending date")


print(Enddate)

output:

2023-09-09
how many days to add? 10
2023-09-19

10. Write a program to count the numbers of characters in the string and store them in a
dictionary data structure.

def char_frequency(str):
dict={}

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

for n in str:
keys=dict.keys()
if n in keys:
dict[n]+=1
else:
dict[n]=1
return dict

str1=input("Enter a string:")
print("The frequency of each character in the string as dictionary")
print(char_frequency(str1))

Output:

Enter a string:MALAYALAMKANNADA
The frequency of each character in the string as dictionary
{'M': 2, 'A': 7, 'L': 2, 'Y': 1, 'K': 1, 'N': 2, 'D': 1}

11. Write a program to count frequency of characters in a given file

def char_frequency(str1):
dict={}
for n in str1:

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

keys=dict.keys()
if n in keys:
dict[n]+=1
else:
dict[n]=1
return dict

str=input("Enter file name to read from :")


getfile= open(str).read()
D=char_frequency(getfile)
print("the frequency of each character in the file")
for k,v in D.items():
print(k,v)

Note:create text document in the same folder where your lab program is saved

Output:
Enter file name to read from :hello.txt
the frequency of each character in the file
S1
T2
3
C2
L4
A3
R2
E4
O2
G2
B1
N1
12. Using a numpy module create an array and check the following:
1) type of array
2) Axes of array
3) Shape of array
4) Type of elements in array

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

import numpy as np

arr=np.array([[1,2,3],[4,2,5]])
print("Array is of type:",type(arr))
print("no.of dimensions:",arr.ndim)
print("Shape of array:",arr.shape)
print("Size of array:",arr.size)
print("Array stores elements of type:",arr.dtype)

Output:

Array is of type: <class 'numpy.ndarray'>


no.of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int32

13. Write a python program to concatenate the dataframes with two different
objects.

import pandas as pd
one=pd.DataFrame({'Name':['Deepak','Joseph'], 'age':[19,20]}, index=[1,2])

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

two=pd.DataFrame({'Name':['Riya','Allen'], 'age':[20,21]}, index=[3,4])


print(pd.concat([one,two]))

Output:

Name age
1 Deepak 19
2 Joseph 20
3 Riya 20
4 Allen 21

14. Write a python code to read a csv file using pandas module and print the
first and last five lines of a file.

#create age.csv in the current directory where you have .py file

import pandas as pd

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

df=pd.read_csv('age.csv')

print('------------------------')
print(df.head())
print('--------')
print(df.tail())

Output
------------------------
NAME AGE
0 Aditya 22
1 Sharon 33
2 Dimple 55
3 Tiya 66
4 Fida 77
--------
NAME AGE
4 Fida 77
5 Tina 22
6 Helna 33
7 Ron 55
8 Sweden 34

(Note: how to create csv file


1.open Microsoft excel
2.underneath file name at the bottom of the save screen you will see option “save
as type” in this field select “CSV(comma delimited)”)
3. two dialogue box will appear (click ‘ok’ and ‘yes’)

15. Write python program which accepts the radius of a circle from user and
computes the area (use math module)

import math as M
radius = float(input("Enter the radius of the circle: "))

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

area_of_circle = M.pi*radius*radius
circumference_of_circle = 2*M.pi*radius
print("the area of circle is", area_of_circle)
print("the circumference of circle is", circumference_of_circle)

Output:

Enter the radius of the circle: 10


the area of circle is 314.1592653589793
the circumference of circle is 62.83185307179586

16. Use the following data(load it as CSV file) for this exercise. Read this file
using Pandas or Numpy or using in-built matplotlib function.

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

a) Get total profit of all months and show line plot with the following Style
properties generated line plot must include following Style properties:-
 Line Style dotted and Line-color should be blue
 Show legend at the lower right location
 X label name – months
 Y label name – sold units
 Line width should be 4
b) Display the number of units sold per month for each product using multiline
plots.(i.e. Separate plotline for each product)

c) Read chair and table product sales data and show it using the bar chart.
 The bar chart should display the number of units sold per month for each
product. Add a separate bar for each product in the same chart.

d) Read all product sales data and show it using the stack plot.

(note:save above data as Book1.csv in the same folder where pgm16.py is saved)

a.
Get total profit of all months and show line plot with the following Style properties
generated line plot must include following Style properties:-
 Line Style dotted and Line-color should be blue

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

 Show legend at the lower right location


 X label name – months
 Y label name – sold units
 Line width should be 4

import pandas as pd
import matplotlib.pyplot as plt

df=pd.read_csv("Store.csv")
profitList=df['Total_units'].tolist()
monthList=df['Months'].tolist()

plt.plot(monthList,profitList,label='Profit Details',
color='b',marker='o',markerfacecolor='k',
linestyle='--',linewidth=4)

plt.xlabel('Months')
plt.ylabel('Sold units')
plt.legend(loc='lower right')
plt.title('Sales Details')
plt.show()

Output:

b.Display the number of units sold per month for each product using multiline
plots.(i.e. Separate plotline for each product)

import pandas as pd

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

import matplotlib.pyplot as plt

df=pd.read_csv("Store.csv")
monthList=df['Months'].tolist()
y1=df['Pen'].tolist()
y2=df['Book'].tolist()
y3=df['Marker'].tolist()
y4=df['Chair'].tolist()
y5=df['Table'].tolist()
y6=df['Pen_stand'].tolist()

plt.plot(monthList,y1,label='Pen',marker='o',linewidth=4)
plt.plot(monthList,y2,label='Book',marker='*',linewidth=3)
plt.plot(monthList,y3,label='Marker',marker='o',linewidth=4)
plt.plot(monthList,y4,label='Chair',marker='*',linewidth=4)
plt.plot(monthList,y5,label='Table',marker='o',linewidth=3)
plt.plot(monthList,y6,label='Pen_stand',marker='*',linewidth=4)

plt.xlabel('Month Number')
plt.ylabel('Sales units in number')
plt.legend(loc='upper left')
plt.xticks(monthList)
plt.yticks([200,400,600,800,1000,2000,4000,8000,10000,20000])
plt.title('Sales Data')
plt.show()

Output:

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

c. Read chair and table product sales data and show it using the bar chart.
 The bar chart should display the number of units sold per month for each
product. Add a separate bar for each product in the same chart.

import pandas as pd
import matplotlib.pyplot as plt

df=pd.read_csv("Store.csv")
monthList=df['Months'].tolist()
y1=df['Chair'].tolist()
y2=df['Table'].tolist()

plt.bar([a-0.25 for a in monthList],y1,width=0.25,label='Chair',align='edge')


plt.bar([a+0.25 for a in monthList],y2,width=-0.25,label='Table',align='edge')

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

plt.xlabel('Month Number')
plt.ylabel('Sales units in number')
plt.legend(loc='upper left')
plt.title('Sales data')
plt.xticks(monthList)
plt.grid(True,linewidth=1,linestyle="--")
plt.title('Chair & Table Sales')
plt.show()

Output:

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

d. Read all product sales data and show it using the stack plot.

import pandas as pd
import matplotlib.pyplot as plt

df=pd.read_csv("Store.csv")
monthList=df['Months'].tolist()

y1=df['Pen'].tolist()
y2=df['Book'].tolist()
y3=df['Marker'].tolist()
y4=df['Chair'].tolist()
y5=df['Table'].tolist()
y6=df['Pen_stand'].tolist()

plt.plot([],[],color='m',label='Pen',linewidth=5)
plt.plot([],[],color='c',label='Book',linewidth=5)
plt.plot([],[],color='r',label='Marker',linewidth=5)
plt.plot([],[],color='k',label='Chair',linewidth=5)
plt.plot([],[],color='g',label='Table',linewidth=5)
plt.plot([],[],color='y',label='Pen_stand',linewidth=5)

plt.stackplot(monthList,y1,y2,y3,y4,y5,y6,colors=['m','c','r','k','g','y'])

plt.xlabel('Month Number')
plt.ylabel('Sales Units in Number')

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24

plt.title('All product sales data using Stack Plot')


plt.legend(loc='upper left')
plt.show()

Output:

Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013

You might also like