Python Lab Manual
Python Lab Manual
a=10;
b=11.5;
c=2.0+5j;
print("a is Type of ",type(a))
print ("b is Type of ",type(b))
print("c is Type of ",type(c))
l=[1,2,3,4,5]
print("l is type of",type(l))
t=(1,2,3,4,5)
print("t is of type",type(t))
student_id={111,112,113,114,115}
print("student_id is Type of ",type(student_id))
example={1:"A",2:"B",3:"C",4:"D"}
print("capital is Type of ",type(example))
message="Good Morning"
print("message is Type of ",type(message))
print("True is type of ",type(True))
Out Put:-
a is Type of <class 'int'>
b is Type of <class 'float'>
c is Type of <class 'complex'>
l is type of <class 'list'>
t is of type <class 'tuple'>
student_id is Type of <class 'set'>
capital is Type of <class 'dict'>
message is Type of <class 'str'>
True is type of <class 'bool'>
2.Create a list and perform the following methods
1) insert() 2) remove() 3) append()
4) len() 5) pop() 6) clear()
list = [1, 2, 3, 4]
print(list)
#append() function
list.append(5)
print("Updated List : ",list)
#len () function
print("list length=",len(list))
# insert() function
list.insert(0, 7)
print("New List: ",list)
#remove function
print("list after remove() fuction",list.remove(2))
print(list)
#pop function()
print("poping the element ",list.pop(0))
oldlist=print(list)
#clear() fuction
print("list after using clear() function")
newlist = list.clear()
print(newlist)
OUTPUT:-
[1, 2, 3, 4]
Updated List : [1, 2, 3, 4, 5]
list length= 5
New List: [7, 1, 2, 3, 4, 5]
list after remove() fuction None
[7, 1, 3, 4, 5]
poping the element 7
[1, 3, 4, 5]
list after using clear() function
None
OUTPUT:-
tuple after adding the elements: (1, 2, 3, 4, 5)
the length of the tuple: 5
True
False
the elements of tuple are
1
2
3
4
5
OUTPUT:-
1. Addition
2. Subtraction
3. Multiplication
4. Division
>>>1
Enter a: 10
Enter b: 25
sum = 35
1. Addition
2. Subtraction
3. Multiplication
4. Division
>>>3
Enter a: 20
Enter b: 60
Mul = 1200
OUTPUT:-
Input a number: 100
It is positive number
7. Write a program for filter() to filter only even numbers from a given list.
def even(x):
return x % 2 == 0
a = [2, 5, 7, 8, 10, 13, 16]
result = filter(even, a)
print('Original List :', a)
print('Filtered List :', list(result))
OUTPUT:-
Original List : [2, 5, 7, 8, 10, 13, 16]
Filtered List : [2, 8, 10, 16]
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)
print(b)
OUTPUT:-
2023-02-27 11:48:54.824689
2023-02-27 11:48:54.824688
9. Write a python program to add some days to your present date and print the date added.
from datetime import datetime, timedelta
#print today's date time
print(datetime.today())
new_date = datetime.today() + timedelta(12)
#print new date time after addition of days to the current date
print (new_date)
OUTPUT:-
2023-02-27 11:50:48.704257
2023-03-11 11:50:48.719867
10. Write a program to count the numbers of characters in the string and store them in a
dictionary data structure.
str=input("enter string : ")
f = {}
for i in str:
if i in f:
f[i] += 1
else:
f[i] = 1
print(f)
OUTPUT:-
enter string : RamaKrishna
{'R': 1, 'a': 3, 'm': 1, 'K': 1, 'r': 1, 'i': 1, 's': 1, 'h': 1, 'n': 1}
OUTPUT:-
this senetences arent meant to be meaningfull on prupose so if you are reading it JUST STOP
t:6
h:1
i:5
s:5
: 16
e : 11
n:8
c:1
a:5
r:4
m:2
o:5
b:1
g:2
f:2
u:3
l:2
p:2
y:1
d:1
J:1
U:1
S:2
T:2
O:1
P:1
:1
{'t': 6, 'h': 1, 'i': 5, 's': 5, ' ': 16, 'e': 11, 'n': 8, 'c': 1, 'a': 5, 'r': 4, 'm': 2, 'o': 5, 'b': 1, 'g': 2, 'f': 2, 'u': 3,
'l': 2, 'p': 2, 'y': 1, 'd': 1, 'J': 1, 'U': 1, 'S': 2, 'T': 2, 'O': 1, 'P': 1, '\n': 1}
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.
import numpy as np
narray = np.array([[1, 2, 3],["a", "b", "c"]])
print(f"Type of an array: {type(narray)}")
print(f"Dimension of an array: {narray.ndim}")
print(f"Shape of an array: {narray.shape}")
print(f"DataType of an array elements: {narray.dtype.type}")
OUTPUT:-
Type of an array: <class 'numpy.ndarray'>
Dimension of an array: 2
Shape of an array: (2, 3)
DataType of an array elements: <class 'numpy.str_'>
13. Write a python program to concatenate the data frames with two different objects.
import pandas as pd
one=pd.DataFrame({'Name':['teju','gouri'],'age':[19,20]},index=[1,2])
two=pd.DataFrame({'Name':['suma','nammu'],'age':[20,21]},index=[3,4])
print(pd.concat([one, two]))
OUTPUT:-
Name age
1 teju 19
2 gouri 20
3 suma 20
4 nammu 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.
import csv
import pandas as pd
data = pd.read_csv(data.csv)
print(data.head(1))
print(data.tail(5))
OUTPUT:-
Months Pen Book Marker ... Table Pen stand Total units Total profit
0 1 2500 1500 5200 ... 1200 1500 21100 211000
[1 rows x 9 columns]
Months Pen Book Marker ... Table Pen stand Total units Total profit
7 8 3700 1400 5860 ... 2860 1400 36140 361400
8 9 3540 1780 6100 ... 2100 1780 23400 234000
9 10 1990 1890 8300 ... 2300 1890 26670 266700
10 11 2340 2100 7300 ... 2400 2100 41280 412800
11 12 2900 1760 7400 ... 1800 1760 30020 300200
[5 rows x 9 columns]
15. Write a python program which accepts the radius of a circle from user and computes
the area (use math module)
import math
radius=int(input('enter the radius:'))
area=math.pi*radius*radius
print('Area of a circle is', area)
OUTPUT:-
enter the radius:25
Area of a circle is 1963.4954084936207
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.
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.
import csv
import pandas as pd
from matplotlib import pyplot as plt
def common():
plt.xticks(data["Months"])
plt.xlabel("Months")
plt.ylabel("Sold Units")
plt.legend()
data = pd.read_csv("data.csv")
plt.figure()
plt.title("a. Get total profit of all months with blue dotted line & width of 4 &\n label x,y, as
Months and Sold Units & show legend at lower right")
plt.plot(data["Months"], data["Total profit"], color='blue', linestyle='dotted', linewidth=4,
label="units")
common()
plt.legend(loc="lower right")
# (ii)
plt.figure()
plt.title("b. Display the number of units sold per month for each product using\nmultiline plots")
for product in data.columns[1:7]:
plt.plot(data["Months"], data[product], label=product)
common()
# (iii)
plt.figure()
plt.title("c. Read chair and table product sales data and show it using the bar chart")
plt.bar(data["Months"] - 0.2, data["Chair"], 0.4, label="Chair")
plt.bar(data["Months"] + 0.2, data["Table"], 0.4, label="Table")
common()
# (iv)
d =plt.figure()
plt.title("d. Read all product sales data and show it using the stack plot")
clmn = data.columns[:7]
plt.stackplot(data["Months"], data[clmn].T, labels = data.keys())
common()
plt.show()