Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Lab_Manual_Python

Uploaded by

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

Lab_Manual_Python

Uploaded by

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

CONTENTS

CA-C13T: PYTHON PROGRAMMING


SI.NO TITLE PAGE
NO
1. Write a program to demonstrate basic data type in python 2

2. Create a list and perform the following methods 3


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

3. Create a tuple and perform the following methods 4


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

4. Create a dictionary and apply the following methods 5


1) Print the dictionary items 2) access items 3) use get() 4)change values 5) use
len()

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


1. To perform addition 2. To perform subtraction
3. To perform multiplication 4. To perform division
6. Write a python program to print a number is positive/negative using if-else. 7
7. Write a program for filter () to filter only even numbers from a given list. 8
8. Write a python program to print date, time for today and now. 9
9. Write a python program to add some days to your present date and print the 10
date added.
10. Write a program to count the numbers of characters in the string and store 11
them in a dictionary data Structure.
11. Write a program to count frequency of characters in a given file. 12
12. Using a numpy module create an array and check the following: 1. Type of 13
array 2. Axes of array 3. Shape
13. Write a python program to concatenate the dataframes with two different 14
objects.
14. Write a python code to read a csv file using pandas module and print the first 15
and last five lines of a file.
15. Write a python program which accepts the radius of a circle from user and 16
computes the area (use math module).
16. Use the following data (load it as CSV file) for this exercise. Read this file using 17-20
Pandas or NumPy or using in-built matplotlib function.

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

a= 20
print('The data type of a is',type(a))
b= 20.5
print('The data type of b is',type(b))
c= 2+1j
print('The data type of c is',type(c))
d=[1,2,3,4,5]
print('The data type of d is',type(d))
e=(9,8,7,6)
print('The data type of e is',type(e))
f={'a':1,'b':2,'c':3}
print('The data type of f is',type(h))

OUTPUT:
The data type of a is <class 'int'>
The data type of b is <class 'float'>
The data type of c is <class 'complex'>
The data type of d is <class 'list'>
The data type of e is <class 'tuple'>
The data type of f is <class 'dict'>

2
2. Create a list and perform the following methods
1) insert()
2) remove()
3) append()
4) len()
5) pop()
6) clear()

l=[10,11,12,13,14,12,15]
print('Number of elements in a list is: ',len(l))
print('Deleted Element using pop() is: ',l.pop())
l.insert(2,30)
print('New list after insert method is: ', l)
l.remove(12)
print('New list after remove method is: ',l)

l.append(50)
print('New list after append method is: ',l)
l.clear()
print('New list after clear method is: ',l)

OUTPUT:
Number of elements in a list is: 7
Deleted Element using pop() is: 15
New list after insert method is: [10, 11, 30, 12, 13, 14, 12]
New list after remove method is: [10, 11, 30, 13, 14, 12]
New list after append method is: [10, 11, 30, 13, 14, 12, 50]
New list after clear method is: []

3
3. Create a tuple and perform the following methods
1) Add items
2) len()
3) Check for item in tuple
4) Access items
t=(12,13,14,12,15,16)
print('Number of elements in a tuple is: ',len(t))
t=t+(2,5)
print('New tuple is:',t)
print('check whether 13 exists in tuple: ',13 in t)
print('check whether 20 exists in tuple: ',20 in t)
print('Accessing tuple items:', t[2:5])

OUTPUT:

Number of elements in a tuple is: 6


New tuple is: (12, 13, 14, 12, 15, 16, 2, 5)
check whether 13 exists in tuple: True
check whether 20 exists in tuple: False
Accessing tuple items: (14, 12, 15)

4
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().
d={1:'c',2:'ds',3:'dbms',4:'java',5:'ca'}
print('Dictionary items are: ',d)
print('Number of Elements in dictionary :',len(d))
print('Access items as: ' , d.items())
print('usage of get() method:' , d.get(3))
d[5]='python'
print('New dictionary after changing the value of 5th element: ',d)

OUTPUT:

Dictionary items: {1: 'c', 2: 'ds', 3: 'dbms', 4: 'java', 5: 'ca'}


Number of Elements in dictionary: 5
Access items as: dict_items([(1, 'c'), (2, 'ds'), (3, 'dbms'), (4, 'java'), (5, 'ca')])
usage of get() method: dbms
New dictionary after changing the value of 5th element: {1: 'c', 2: 'ds', 3: 'dbms', 4:
'java', 5: 'python'}

5
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

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
x =eval(input('Enter 1st Number:'))
y = eval(input('Enter 2nd Number:'))
while True:
ch = input('\nEnter the Operator (+,-,*,/):')
if ch=='+':
print("\n Addition of two numbers= " , add(x,y))
elif ch=='-':

print("\n Subtraction of two numbers= " , sub(x,y))


elif ch=='*':
print("\n Multiplication of two numbers = " , mul(x,y))
elif ch=='/':
print("\n Division of two numbers = " , div(x,y))
else:
print("\nInvalid Operator!")
break

OUTPUT:

Enter 1st Number:12


Enter 2nd Number:6
Enter the Operator (+,-,*,/):+
Addition of two numbers= 18
Enter the Operator (+,-,*,/):-
Subtraction of two numbers= 6
Enter the Operator (+,-,*,/):*
Multiplication of two numbers = 72
Enter the Operator (+,-,*,/):/
Division of two numbers = 2.0
6
6. Write a python program to print a number is positive/negative
using if-else.
n = float(input('Input a number: '))
if n>=0:
print(n, "is a positive number")
else:
print(n, "is a negative number")

OUTPUT:
Input a number: 23
23.0 is a positive number

Input a number: -67


-67.0 is a negative number

7
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('Even Numbers are :',list(result))

OUTPUT:
original list : [2, 5, 7, 8, 10, 13, 16]
Even Numbers are : [2, 8, 10, 16]

8
8. Write a python program to print date, time for today and now.
from datetime import datetime
print("Today's Date =", datetime.now().date())
print("Time =", datetime.now().time())

OUTPUT:
Today's Date = 2022-10-11
Time = 09:09:52.636709

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

from datetime import timedelta, date


newdate = date.today() + timedelta(days=5)
print("Present date: ",date.today())
print("New Date after adding 5 days to Present date: ",newdate)

OUTPUT:
Present date: 2022-10-11
New Date after adding 5 days to Present date: 2022-10-16

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

str=input("Enter a String: ")


L=len(str)
d={str:L}
print("Dictionary is : ",d)

OUTPUT:
Enter a String: python
Dictionary is : {'python': 6}

11
11. Write a program to count frequency of characters in a given
file.
f=open(“a.txt”,’r’)
c=f.read()
print(“content of file is:”,c)
freq={ }
for i in c:
if i in freq:
freq[i] +=1
else:
freq[i]=1
print(“Frequency of each char in a file is:”,freq)

OUTPUT:
Frequency of each char in a file is: {'W': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 4, 'm': 3, ' ': 3,
't': 2, 'P': 2, 'y': 1, 'h': 1, 'n': 2, 'r': 2, 'g': 2, 'a': 1, 'i': 1}

12
12. Using a numpy module create an array and check the
following:
1. Type of array 2. Axes of array 3. Shape
import numpy as np
arr=np.array([[1,2,3,4,5]])
print(“Array elements are:”,arr)

#type of an array
print(“datatype of array:”,type(arr))

#Axes of array
axess=np.swapaxes(arr,0,1)
print(“converted array is:”,axess)

#shape of an array

arr2=np.array([[2,2],[6,7]]) #2D array


arr3=np.array([[[1,2],[2,7]],[[4,5],[5,6]]]) #multi dimensional array
print(“Number of rows and columns in array matrix is:”,arr.shape)
print(“Number of rows and columns in array matrix is:”,arr2.shape)
print(“Number of blocks, rows and columns in array matrix is:”,arr3.shape)

#type of elements in array


print(arr.dtype)
print(arr2.dtype)
print(arr3.dtype)

OUTPUT:
Array elements are: [[1 2 3 4 5]]
datatype of array: <class 'numpy.ndarray'>
converted array is: [[1]
[2]
[3]
[4]
[5]]
Number of rows and columns in array matrix is: (1, 5)
Number of rows and columns in array matrix is: (2, 2)
Number of blocks, rows and columns in array matrix is: (2, 2, 2)
int64
int64
int64
13
13. Write a python program to concatenate the dataframes with
two different objects.
import pandas as pd
import numpy as np
df1=pd.DataFrame({'A':['A0','A1','A2','A3'],'B':['B0','B1','B2','B3'],'C':['C0','C1','C2','C
3']},index=[0,1,2,3])
df2=pd.DataFrame({'A':['A4','A5','A6','A7'],'B':['B4','B5','B6','B7'],'C':['C4','C5','C6','C
7']},index=[4,5,6,7])
print(pd.concat([df1,df2]))

OUTPUT:

A B C
0 A0 B0 C0
1 A1 B1 C1
2 A2 B2 C2
3 A3 B3 C3
4 A4 B4 C4
5 A5 B5 C5
6 A6 B6 C6
7 A7 B7 C7

14
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 pandas as pd
data=pd.read_csv('upload.csv')
print(data)

OR
import pandas as pd
#to read a csv file
data=pd.read_csv('upload.csv')
#to print only five lines
print(data.head())
print(data.tail())

OUTPUT:
Name Marks Section
xyz 34 3
abc 35 3
ert 40 3
asf 34 2
fdg 34 6
jjg 45 3
ere 40 3

15
15. Write a python program which accepts the radius of a circle
from user and computes the area (use math module).
from math import pi
r = float(input ("Enter radius of the circle : "))
print ("The area of the circle = " , (pi * r**2))

OUTPUT:
Enter radius of the circle : 5
The area of the circle = 78.53981633974483

16
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 four

import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv("C:/Users/Sri/Desktop/Salesdata.csv")
total_profit=df["Total Profit"]
plt.plot(total_profit,color='blue',marker='o',linestyle='dotted',label='Total
Profit',linewidth=4)
plt.xlabel("Months")
plt.ylabel("Total Points")
plt.title("Profit trend of all products")
plt.legend(loc="lower right")
plt.xticks(range(len(df)),df['Months'],rotation=45)
plt.show()

17
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
import matplotlib.pyplot as plt
data = pd.read_csv("C:/Users/Student/Desktop/Salesdats.csv")
plt.plot(data.months,data.pen,color='blue',marker='o',label="pen",linestyle='solid')
plt.plot(data.months,data.book,color='red',marker='o',label="book",linestyle='dotted')
plt.plot(data.months,data.marker,color='green',marker='o',label="marker",linestyle='d
ashed')
plt.plot(data.months,data.chair,color='yellow',marker='o',label="chair",linestyle=':')
plt.plot(data.months,data.table,color='purple',marker='o',label="table")
plt.plot(data.months,data.penstand,color='orange',marker='o',label="pen
stand",linestyle='solid')
plt.xlabel("months")
plt.ylabel("sold_units")
plt.title("sales trend of all products")
plt.legend(loc="upper left")
plt.show()

18
19
c. Read chair, 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
data = pd.read_csv("C:/Users/Student/Desktop/Salesdats.csv")
plt.bar(data.months,data.chair,color='black',width=0.4)
plt.bar(data.months+0.4,data.table,color='red',width=0.4)
plt.legend(["chair","table"],loc="upper left")
plt.xlabel("month")
plt.ylabel("sold units per months")
plt.show()

20

You might also like