Python Programs
Python Programs
a=10
b=11.6
c=20.06j
abc=["Hello",1,4,"Shreya"]
abcd=("Hey",6,8)
xyz={"name":"Shreya","age":19,"college":"St Pauls"}
pp={5,8,9,10}
OUTPUT
2. Create a list and perform following methods
1)Insert() 2) remove() 3) append() 4)Len() 5)pop() 6)clear()
#program to perform list operations
#18/11/22
iList=[10,20,30,40,50,60,70,80,90,100]
print("After Creation:",iList)
iList.append(111)
print("After appending:",iList)
iList.sort()
print("After sorting List = ",iList)
iList.remove(80)
print("After removing 80:",iList)
iList.insert(2,100)
print("After inserting:",iList)
iList.clear()
print("After clearing:",iList)
OUTPUT
3. Create a tuple and perform following methods
1) Add items 2) len() 3) Check for item in tuple 4) Access items
#tuple creation
Tuple = ("Teena", "Meena", "Reena", "Sheela", "Leena")
print("\n Created tuple is :", Tuple)
#append
y.append("Priya")
print("\n After appending to list", y)
y[2] = "Bengaluru"
print("\n After adding the item in the index 2",y)
if "Riya" in Tuple:
print("\n Yes, the item is present in the tuple")
else:
print("\n No, the item is not present in the tuple")
#Creation of dictionary
dict =
{"name":"Shreya","age":19,"course":"BCA","phone":9853435125}
print(" \n Displaying dictionary",dict)
#access dictionary items
val = dict.items()
print("\n The items are:",val)
#using get
print("\n Using gets for getting values",dict.get("name"))
#change values
dict["course"]="BBA"
print("\n After changing values",dict)
#finding the length
print("\n The length of the dictionary is:",len(dict))
OUTPUT
5. Write a program to create a menu with following options
1)To perform addition 2)To perform subtraction
3)To perform multiplication 4)To perfrom division
#9/12/2022
'''print("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(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
OUTPUT
7. Write a program for filter() to filter only even numbers from a
given list
def even(x):
return x%2==0
a=[8,12,17,3,22,33]
result=filter(even,a)
print("Original list",a)
print("Filtered list",list(result))
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)
print(b)
OUTPUT
9. Write a program to add some days to your present date and print
the date added
OUTPUT
10. Write a program to count the numbers of characters in the string
and store them in a dictionary structure
OUTPUT
11. Write a program to count frequency of characters in a given file
import collections
import pprint
file_input = 'D:/demo.txt'
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
a = file_input.split(".")
if a[1] == "txt":
print("It is a text file")
elif a[1]=="cpp":
print("It is a c file")
else:
print('It is a c++ file')
OUTPUT
12. Using 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
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
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
pd.set_option("Display.max_rows",50)
pd.set_option("Display.max_columns",50)
diamonds = pd.read_csv("D:\program14csv.csv")
print("First 5 rows")
print(diamonds.head())
print("Last 5 rows")
print(diamonds.tail())
OUTPUT
16. Use the following data(load it as csv file) for this exercise. Read
this file using NumPy or pandas in-built matplotlib function.
Months Pen Book Marker Chair Table Pen Stand Total unitsTotal 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 29550
8 3700 1400 5860 9960 2860 1400 36140 361400
9 2760 1780 6100 8100 2100 1780 23400 234000
10 2980 1890 8300 10300 2300 1890 26670 266700
11 2340 2100 7300 13300 2400 2100 41280 412800
12 2900 1760 7400 7400 1800 1760 30020 300200
OUTPUT -
b. Display the number of units sold per month for each product
using multiline plots
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv("D:/Book1.csv")
plt.plot(df['Months'],df['Pen'],label='Pen')
plt.plot(df['Months'],df['Book'],label='Book')
plt.plot(df['Months'],df['Marker'],label='Marker')
plt.plot(df['Months'],df['Chair'],label='Chair')
plt.plot(df['Months'],df['Table'],label='Table')
plt.plot(df['Months'],df['Pen Stand'],label='Pen Stand')
plt.plot(xlabel='Months')
plt.plot(ylabel='Total units')
plt.legend()
plt.show()
OUTPUT-
c.
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv("D:/Book1.csv")
plt.bar(df['Months'],df['Chair'],label='Chair')
plt.bar(df['Months'],df['Table'],label='Table')
plt.legend(loc='best')
plt.show()
OUTPUT –
d.
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv("D:/Book1.csv")
a,b=plt.subplots()
b.stackplot(list(df.columns.values)[1:7],df.iloc[:,1:
7],labels=list(df.columns.values)[1:7])
plt.legend(loc='best')
plt.show()
OUTPUT-