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

Python Lab Manual

The document is a Python programming lab manual from Acharya Institute of Graduate Studies, covering various programming tasks including data types, list methods, tuple operations, dictionary manipulations, and basic arithmetic functions. It includes sample code snippets and their outputs for each task, demonstrating fundamental Python concepts and libraries such as NumPy and pandas. The manual serves as a practical guide for students to learn and practice Python programming.

Uploaded by

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

Python Lab Manual

The document is a Python programming lab manual from Acharya Institute of Graduate Studies, covering various programming tasks including data types, list methods, tuple operations, dictionary manipulations, and basic arithmetic functions. It includes sample code snippets and their outputs for each task, demonstrating fundamental Python concepts and libraries such as NumPy and pandas. The manual serves as a practical guide for students to learn and practice Python programming.

Uploaded by

lekhanar14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

ACHARYA INSTITUTE OF GRADUATE STUDIES

(NAAC Re-accredited ‘A’ and Affiliated to Bengaluru City University)


Soladevanahalli, Bengaluru-560107
DEPARTMENT OF COMPUTER APPLICATION
PYTHON PROGRAMMING LAB-MANUAL

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

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

3. Create a tuple and perform the following methods


1) Add items 2) len() 3) check for item in tuple 4)Access items
t=( )
t=t+(1,2,3,4,5)
print("tuple after adding the elements:",t)
print("the length of the tuple:",len(t))
print(3 in t)
print(10 in t)
print("the elements of tuple are")
for i in t:
print(i)

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

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()
print('printing the dictionary item:')
dict1={"name":"suma","regno":321,"course":"BCA","age":19}
print(dict1)
print('accessing the items:')
print(dict1["age"])
print('using get():')
x=dict1.get("regno")
print(x)
print('changing the values in the dictionary:')
dict2={"regno":286}
dict1.update(dict2)
print(dict1)
print('length of dictionary is:',len(dict1))
OUTPUT:-
printing the dictionary item:
{'name': 'suma', 'regno': 321, 'course': 'BCA', 'age': 19}
accessing the items:
19
using get():
321
changing the values in the dictionary:
{'name': 'suma', 'regno': 286, 'course': 'BCA', 'age': 19}
length of dictionary is: 4

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


1. TO PERFORM ADDITITON
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPICATION
4. TO PERFORM DIVISION
Accepts users input and perform the operation accordingly. Use functions with arguments.
def add(a, b):
return a+b
def sub(a, b):
return a-b
def mul(a, b):
return a*b
def div(a, b):
return a/b
print("\n1. Addition \n2. Subtraction \n3. Multiplication \n4. Division")
choice = int(input(">>>"))
a = int(input("Enter a: "))
b = int(input("Enter b: "))
if choice==1:
print("sum = ",add(a,b))
elif choice==2:
print("Sub = ",sub(a,b))
elif choice==3:
print("Mul = ",mul(a,b))
elif choice==4 :
print("Div = ",div(a,b))

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

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


num = int(input("Input a number: "))
if num > 0:
print("It is positive number")
else:
print("It is a negative number")

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}

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


with open("word.txt","r") as file:
data = file.read()
letter_count = {}
for ch in data:
if ch not in letter_count.keys():
letter_count[ch]=1
else:
letter_count[ch]+=1
print(data)
for i in letter_count:
print(i,":",letter_count[i])
print(letter_count)

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.

Pen Total Total


Months Pen Book Marker Chair Table stand units profit
1 2500 1500 5200 9200 1200 1500 21100 211000
2 2630 1200 5100 6100 2100 1200 18330 183300
3 2140 1340 4550 9550 3550 1340 22470 224700
4 3400 1130 5870 8870 1870 1130 22270 222700
5 3600 1740 4560 7760 1560 1740 20960 209600
6 2760 1555 4890 7490 1890 1555 20140 201400
7 2980 1120 4780 8980 1780 1120 29550 295500
8 3700 1400 5860 9960 2860 1400 36140 361400
9 3540 1780 6100 8100 2100 1780 23400 234000
10 1990 1890 8300 10300 2300 1890 26670 266700
11 2340 2100 7300 13300 2400 2100 41280 412800
12 2900 1760 7400 14400 1800 1760 30020 300200

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

You might also like