Pylab Manual
Pylab Manual
CA-C15L: PYTHON
PROGRAMMING LAB
III SEM BCA
Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24
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
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
#creating a tuple
rainbow=("v","i","b","g","y","o","r")
print(rainbow)
colour=("violet","blue","green","yellow","orange","red")
print(colour)
"""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:
Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24
#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:
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
Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24
Output:
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]
def f(X):
return X%2==0
M=list(filter(f,L1))
print("Original list: ",L1)
print("Filtered list: ",M)
Output:
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.
Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013
Python lab manual 2023-24
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}
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
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:
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
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
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:
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
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
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()
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
Output:
Ms. Bincy Joseph, Department of Computer Science, St. Claret College, Bangalore-560013