You are on page 1of 67

Python Programming

JOURNAL

MCA-1(SEM-2)

61291401- Ashik Ali (MCA-1 sem-2) Page 1


JSPM’s
JAYAWANT INSTITUTE OF MANAGEMENT STUDIES
(NAAC “A” Grade, Approved by AICTE, New Delhi,Recognised by Gov,of Maharashtra &
Affiliated to Pune University)
S. No. 80/2, Pune-Mumbai Bypass Highway, Tathawade, Pune – 411033.
Phone: +91-20-64731454/55 Telefax: +91-20-22933424.
E-mail: jims1@vsnl.net Website: www.jspm.edu.in

Prof. T. J. Sawant Dr. Priyanka A. Singh


B.E.(Elec.), PGDM, Ph.D B.Sc. (Hons), MBA, Ph. D.
Founder- Secretary Director

Date: 11/09/2021

CERTIFICATE

This is to certify that Mr. / Miss. Ashik Yaseen Ali


R. No. _61291401 is the student of MCA – 1st Year and has
completed successfully the practical examination in the subject
“Python Programming Lab” in September, 2021.

The practical examination is accomplished adequately & submitted


journal in partial fulfillment of MCA-I Semester-II curriculum as
per the rules of Savitribai Phule Pune University.

PROF. LEENA DESHMUKH


PROF. DEEPAK PANDITA DR. PRIYANKA SINGH
SUBJECT TEACHERS DIRECTOR

61291401- Ashik Ali (MCA-1 sem-2) Page 2


INDEX

Sr.no Program Name Page

1 Python installation and configuration with 5


windows and Linux
2 Programs for understanding the data types, 7
control flow statements, blocks and loops
3 Programs for understanding functions, use 12
of built in functions, user defined functions
4 Programs to use existing modules, packages 14
and creating modules, packages
5 Programs for implementations of all object- 15
oriented concepts like class, method,
inheritance, polymorphism etc
6 Programs for parsing of data, validations like 22
Password, email, URL, etc.
7 Programs for Pattern finding should be 23
covered.
8 Programs covering all the aspects of 25
Exception handling, user defined exception,
Multithreading should be covered.
9 Programs demonstrating the IO operations 27
like reading from file, writing into file from
different file types like data file, binary file,
etc.
10 Programs to perform searching, adding, 31
updating the content from the file
61291401- Ashik Ali (MCA-1 sem-2) Page 3
11 Program for performing CRUD operation 33
with MongoDB and Python
12 Basic programs with NumPy as Array, 44
Searching and Sorting, date & time and
String handling
13 Programs for series and data frames should 53
be covered
14 Programs to demonstrate data pre- 59
processing and data handling with data
frame
15 Program for data visualization should be 61
covered.

61291401- Ashik Ali (MCA-1 sem-2) Page 4


1] Python installation and configurati

on with windows and Linux

Q. Write down steps of python installation with windows Step

1: Select Version of Python to Install

Step 2: Download Python Executable Installer

61291401- Ashik Ali (MCA-1 sem-2) Page 5


Step 3: Run Executable Installer

61291401- Ashik Ali (MCA-1 sem-2) Page 6


2] Programs for understanding the data types, control flow statements, blocks
and loops

Q. In this project, you’ll learn how to create 2 random teams from a list of players

Program-

from random import choice

#create a list of players from a file

players = []

file = open('players.txt', 'r')

players = file.read().splitlines()

print('Players:', players)

#create a list of team names from a file

teamNames = []

file = open('teamNames.txt', 'r')

61291401- Ashik Ali (MCA-1 sem-2) Page 7


teamNames = file.read().splitlines()

print('Team names:', teamNames)

#create empty team lists

teamA = []

teamB = []

#loop until there are no players left

while len(players) > 0:

#choose a random player for team A

playerA = choice(players)

teamA.append(playerA)

#remove the player from the players list

players.remove(playerA)

#break out of the loop if there are no players left

if players == []:

break

#choose a random player for team B

playerB = choice(players)

teamB.append(playerB)

#remove the player from the players list

players.remove(playerB)

#choose random team names for the 2 teams

teamNameA = choice(teamNames)

teamNames.remove(teamNameA)

61291401- Ashik Ali (MCA-1 sem-2) Page 8


teamNameB = choice(teamNames)

teamNames.remove(teamNameB)

#print the teams

print('\nHere are your teams:\n')

print(teamNameA, teamA)

print(teamNameB, teamB)

OUTPUT-

Q. Write functions to do queue operations (enQueue, deQueue, view, quit) using lists

Program-

class Queue:

def __init__(self):

self.items = []

def is_empty(self):

return self.items == []

def enqueue(self, data):

61291401- Ashik Ali (MCA-1 sem-2) Page 9


self.items.append(data)

def dequeue(self):

return self.items.pop(0)

q = Queue()

while True:

print('enqueue <value>')

print('dequeue')

print('view')

print('quit')

do = input('What would you like to do? ').split()

operation = do[0].strip().lower()

if operation == 'enqueue':

q.enqueue(int(do[1]))

elif operation == 'dequeue':

if q.is_empty():

print('Queue is empty.')

else:

print('Dequeued value: ', q.dequeue())

elif operation=='view':

if q.is_empty():

61291401- Ashik Ali (MCA-1 sem-2) Page 10


print('Queue is empty.')

else:

print('Dequeued value: ', q.dequeue())

elif operation == 'quit':

break

OUTPUT-

Q] Write a Python program to check whether given number is Armstrong number

Program-

# Python program to check if the number is an Armstrong number or not

# take input from the user

num = int(input("Enter a number: "))

# initialize sum

sum = 0

# find the sum of the cube of each digit

temp = num

61291401- Ashik Ali (MCA-1 sem-2) Page 11


while temp > 0:

digit = temp % 10

sum += digit ** 3

temp //= 10

# display the result

if num == sum:

print(num,"is an Armstrong number")

else:

print(num,"is not an Armstrong number")

OUTPUT-

3] Programs for understanding functions, use of built in functions, user defined


functions

Q. Write a recursive function to make summation of list elements


Program-

def recursive_list_sum(data_list):

total = 0

for element in data_list:

if type(element) == type([]):

total = total + recursive_list_sum(element)

61291401- Ashik Ali (MCA-1 sem-2) Page 12


else:

total = total + element

return total

print( recursive_list_sum([10, 20, [3,4],[35,65]]))

OUTPUT-

Q. In this project, you are passing the secret message (encrypted) to your colleague, your
colleague know key to decrypt it

Program-

from cryptography.fernet import Fernet

# we will be encryting the below string.

message = "hello it is message converter"

# generate a key for encryptio and decryption

# You can use fernet to generate

# the key or use random key generator

# here I'm using fernet to generate key

key = Fernet.generate_key()

# Instance the Fernet class with the key

fernet = Fernet(key)

# then use the Fernet class instance


61291401- Ashik Ali (MCA-1 sem-2) Page 13
# to encrypt the string string must must

# be encoded to byte string before encryption

encMessage = fernet.encrypt(message.encode())

print("original string: ", message)

print("encrypted string: ", encMessage)

# decrypt the encrypted string with the

# Fernet instance of the key,

# that was used for encrypting the string

# encoded byte string is returned by decrypt method,

# so decode it to string with decode methos

decMessage = fernet.decrypt(encMessage).decode()

print("decrypted string: ", decMessage)

OUTPUT-

4] Programs to use existing modules, packages and creating modules, packages

Q. It’s important to protect your personal information online, and in this


project you’ll create a program to generate passwords for you. The passwords
will be random, so no one will be able to guess them!
Program-

import random

61291401- Ashik Ali (MCA-1 sem-2) Page 14


import string

print('hello, Welcome to Password generator!')

length = int(input('\nEnter the length of password: '))

lower = string.ascii_lowercase

upper = string.ascii_uppercase

num = string.digits

symbols = string.punctuation

all = lower + upper + num + symbols

temp = random.sample(all,length)

password = "".join(temp)

print(password)

OUTPUT-

5] Programs for implementations of all object-oriented concepts like class,


method, inheritance, polymorphism etc. (Real life examples must be covered for
the implementation of object oriented concepts)

Q. Design a class employee (name, dept, salary). Write a python program that
should throw an exception when salary is less than 0.
Program-

class Employe:

61291401- Ashik Ali (MCA-1 sem-2) Page 15


name =""

dept=""

salary=0.0

def displaydata(self):

try:

print("=========================================")

print("Name of an Employee is :",self.name)

print("Department of an Employee is: ", self.dept)

if self.salary <= 0.0:

raise ValueError

else:

print("The salary of an employee is : ", self.salary)

except ValueError:

print("The Salary of Employee must be less tham Zero(0)")

print("=============================================")

# n=input("how many employee Data do you wan to enter :")

# for i in range(n):

emp1=Employe()

emp1.name= input("enter the Employee Name : ")

emp1.dept= input("Enter the Department of an Employee : ")

emp1.salary=float(input("enter the salary of an employee : "))

emp1.displaydata()

61291401- Ashik Ali (MCA-1 sem-2) Page 16


OUTPUT-

Q. Define a base class “Item” (item_no, name, price). Derive a class “Discounted_Item”
(discount_percent). A customer buys ‘n’ items. Calculate the total price, total discount and
display the bill using appropriate output formats

Program-

class Item:

item_name={"item1":"cake","item2":"brownie","item3":"choco lava"}

item_Price={"item1":"650","item2":"300","item3":"200"}

item_No={"item1":"154","item2":"238","item3":"459"}

class Discount_item (Item):

discounts={

"item1":"20",

"item2":"15",

"item3":"10"

61291401- Ashik Ali (MCA-1 sem-2) Page 17


}

class Shop(Discount_item):

Customer_name=""

Item_name=[]

selected_item=[]

selected_Price=[]

selected_dis=[]

def bill(self):

for key,value in self.item_name.items():

for n in self.Item_name:

if n == value:

self.selected_item.append(key)

# print(self.selected_item)

for key,value in self.item_Price.items():

for i in self.selected_item:

if i == key:

self.selected_Price.append(value)

# print(self.selected_Price)

for key,value in self.discounts.items():

for i in self.selected_item:

61291401- Ashik Ali (MCA-1 sem-2) Page 18


if i==key:

self.selected_dis.append(value)

# print(self.selected_dis)

print("================BILL============")

print("Name : ", self.Customer_name)

print("Selected items are")

for i in self.Item_name:

print(i)

sum=0

for i in self.selected_Price:

sum+=int(i)

print("Total Amount of items is : ",sum)

dis=0

for i in self.selected_dis:

dis+=int(i)

print("Total discout of items is : ", dis)

print("Total Bill Rs is : ", sum-((dis/100)*sum))

print("=========================================")

def menu(self):

print("================Menu===================")

print("Item 1) cake Rs650 \n Item 2) brownie Rs300 \n Item 3) choco lava Rs200 ")

61291401- Ashik Ali (MCA-1 sem-2) Page 19


print("==========================================")

s1=Shop()#Object Created

s1.menu()#The Menu Displayed

s1.Customer_name =input("Enter your name : ")

# n=int(input("How many items do you want to buy : "))

# for i in range(n):

s1.Item_name=list(input("Enter the name of item :").split(" and "))

s1.bill()

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 20


Q. Write a python program to create a Employee class with properties empid, empname,
dept, salary and methods show() [employee details], raisesal() [by 10% who get <40000
salary], using constructor

Program-

class Employee:

def __init__(self, id, name, dept, salary):

self.id = id

self.name = name

self.dept = dept

self.salary = salary

#data = self.id + " " + self.name+ " "+ self.dept

if self.salary > 40000:

print(f" { self.id} {self.name} {self.dept} {self.salary} ")

if self.salary < 40000:

self.raiseSalary()

def raiseSalary(self):

raisedSalary = self.salary + self.salary * 0.1

print(f" Raised Salary of { self.id} {self.name} {self.dept} {self.salary} {raisedSalary}")

obj1 = Employee(1, "swaleeya", "MBA", 50000 )

obj2 = Employee(2, "Purva", "MCA", 30000 )

obj3 = Employee(3, "Ankita", "BCA", 20000 )

61291401- Ashik Ali (MCA-1 sem-2) Page 21


OUTPUT-

6]. Programs for parsing of data, validations like Password, email, URL, etc.

Q. Write a Python program to validate atleast 5 fields of registration form using


regular expression match() method (name only alphabets, address
alphanumeric with (, - _) sp. chars, mobile with 10 digits only, email with (@ .),
gender with Male | Female only )
Program-

import re

name=input('Enter Name = ')

if not re.match(r"(^[a-zA-Z]+$)", name):

print('enter valid name =')

address=input('Enter Address =')

if not re.match(r"(^[a-zA-Z]+$)", address):

print('enter valid address =')

phno=input('Enter Mobile Number = ')

61291401- Ashik Ali (MCA-1 sem-2) Page 22


if not re.match(r"(^[0-9]{10})+$", phno):

print('enter valid mobile number =')

email=input('enter email_id =')

if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z]+$)", email):

print('enter valid email-id =')

gender=input('enter gender =')

if not re.match(r"(male|female+$)", gender):

print('enter valid gender =')

OUTPUT-

7]. Programs for Pattern finding should be covered.

Q. Write a Python program to validate password using regular expression


search() method (password should contain at least 1 lowercase, 1 uppercase, 1
special character, and length between 8 to 20, no whitespaces)
# Python program to check validation of password

# Module of regular expression is used with search()

61291401- Ashik Ali (MCA-1 sem-2) Page 23


import re

password = input("Enter Password: ")

flag = 0

while True:

if (len(password)<8):

flag = -1

break

elif not re.search("[a-z]", password):

flag = -1

break

elif not re.search("[A-Z]", password):

flag = -1

break

elif not re.search("[0-9]", password):

flag = -1

break

elif not re.search("[_@$]", password):

flag = -1

break

elif re.search("\s", password):

flag = -1

break

else:

flag = 0

61291401- Ashik Ali (MCA-1 sem-2) Page 24


print("Valid Password")

break

if flag ==-1:

print("Not a Valid Password")

OUTPUT-

8]. Programs covering all the aspects of Exception handling, user defined
exception, Multithreading should be covered.

Q. Write an application to implement a user defined exception “In Sufficient


Fund Exception”. Read amount from console & check whether entered amount
is available in your account or not. If amount is available then with draw given
amount and if it is not available then trow the exception “In sufficient Fund
Exception” and display how much amount is required to withdraw.
# Python program to create Bankaccount class

# with both a deposit() and a withdraw() function

class Bank_Account:

def __init__(self):

self.balance=0

61291401- Ashik Ali (MCA-1 sem-2) Page 25


print("Hello!!! Welcome to the Deposit & Withdrawal Machine")

def deposit(self):

amount=float(input("Enter amount to be Deposited: "))

self.balance += amount

print("\n Amount Deposited:",amount)

def withdraw(self):

amount = float(input("Enter amount to be Withdrawn: "))

if self.balance>=amount:

self.balance-=amount

print("\n You Withdrew:", amount)

else:

print("\n Insufficient balance ")

def display(self):

print("\n Net Available Balance=",self.balance)

# Driver code

# creating an object of class

s = Bank_Account()

# Calling functions with that class object

61291401- Ashik Ali (MCA-1 sem-2) Page 26


s.deposit()

s.withdraw()

s.display()

OUTPUT-

9]. Programs demonstrating the IO operations like reading from file, writing into file from
different file types like data file, binary file, etc.

Q. Write a python program to create a file called emp.txt and store information about n
persons, in terms of their name, age and salary. Read the file and display the persons whose
salary is more than average salary of all persons.

Program-

class File1:

salaries = []

ave=0.0

sum=0.0

count=0
61291401- Ashik Ali (MCA-1 sem-2) Page 27
simple_str=""

def addData(self,person_name,person_age,person_salary):

file=open("./emp.txt","a")

file.write(f"name : {person_name} \nAge : {person_age} \nSalary :


{person_salary} \n")

file.close()

def display(self):

file=open("emp.txt","r")

for each in file:

print(each)

if("Salary : " in each):

self.salaries.append(each[9:each.find("\n")])

# print(file.read())

print(self.salaries)

for i in self.salaries:

self.sum+=float(i)

self.count+=1

self.ave=self.sum/self.count

print("The Average salary of an Employers : ",self.ave)

file.close()

61291401- Ashik Ali (MCA-1 sem-2) Page 28


file2=open("./emp.txt","r")

print("The Greater salary of an Employees are:")

for anothereach in file2 :

# print("Hello")

self.simple_str+=anothereach

# print(self.simple_str)

if("Salary : " in anothereach):

if float(anothereach[9:anothereach.find("\n")]) > self.ave:

print(self.simple_str)

self.simple_str+=""

file2.close()

file =open("./emp.txt","w")

file.write("")

file.close

f1= File1()

n=int(input("How many Data of Employee do you want to insert ?"))

61291401- Ashik Ali (MCA-1 sem-2) Page 29


for i in range(n):

print("=================person",i+1,"========================")

name =input("Enter the Person Name : ")

age =input("Enter the Person Age : ")

salary= float(input("Enter the Person Salary : "))

print("================================================")

f1.addData(name,age,salary)

f1.display()

Output-

61291401- Ashik Ali (MCA-1 sem-2) Page 30


10]. Programs to perform searching, adding, updating the content from the file.
Q. Write a program that reads a text file & create another file that is identical

61291401- Ashik Ali (MCA-1 sem-2) Page 31


except that every sequence of consecutive blank spaces is replaced by a single
space.
Program-

file1 = open("emp.txt","r")

file2 = open("Express.txt","w")

lst = file1.readlines()

for i in lst :

word = i.split()

for j in word:

file2.write(j +" ")

file2.write("\n")

print("Program has successfully run")

file2.close()

file1.close()

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 32


Q] Write a python program to get the employee details from employee.txt file
(empid, empname, dept, salary) and raise the salary of employees who have
less than 40000 salaries by 10%. After salary raise write all employee data in
new file salaryraise.txt
emp=open("emp.txt","r")

sal=open("salraise.txt","a")

emps=[]

for eps in emp:

emps=eps.split()

print(emps)

if int(emps[3])<40000:

emps[3]=int(emps[3])+(int(emps[3])*0.1)

sal.write("\n"+emps[0]+" "+emps[1]+" "+str(emps[2]))

#emp.close()

sal.close()

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 33


11] Program for performing CRUD operation with MongoDB and Python Q.
Write a python program to perform CRUD operations on MongoDB documents
collection (title, description, by, url, tags, likes, comments):
1. mycol as − > use documentDB > db.createCollection("mycol")

if __name__ == "__main__":
print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
print(client)

db = client['documentDB']
collection = db['myCol']

61291401- Ashik Ali (MCA-1 sem-2) Page 34


2.Insert atleast 3 documents in it using the insert() method

import pymongo

if __name__ == "__main__":
print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
print(client)

db = client['documentDB']
collection = db['myCol']

document1 = {
"_id": 1,
"title": "MongoDB",
"desc": "MongoDB It is a Nosql data base",
"by": "rp Tutorial",
"url": "https://www.rptutorial.com",
"tag":"pymongo",
"likes":2497,
"comments":[
"Best Database",
"Easy to Handle",
"Very lite",
]
}

document2 = {
"_id": 2,
"title": "Laptops",
"desc": "Upcoming Laptops Overview",
"by": "johan",
"url": "https://www.rpgadgets.com",
"tag":"pymongo",
"likes":249,
"comments":[
"Best site ever for laptops",
"All information about laptops in one place"
]
}

61291401- Ashik Ali (MCA-1 sem-2) Page 35


document3 = {
"_id": 3,
"title": "Mobiles",
"desc": "New Mobile Unboxing and Review",
"by": "rahul",
"url": "https://www.rjmobile.com",
"tag": "pymongo",
"likes": 25,
"comments": [
"Right information about mobiles",
"Useful"
]
}

document4 = {
"_id": 4,
"title": "Software Solutions",
"desc": "We Provide All Software Solutions",
"by": "Pranit",
"url": "https://www.pmsoftwaresolution.com",
"tag": "pymongo",
"likes": 40,
"comments": [
"Free Softwares",
"All Software easy to use"
]
}

document5 = {
"_id": 5,
"title": "Computer Hardware's",
"desc": "We Provide All Computer & Laptop Hardware Solutions",
"by": "Vihwas",
"url": "https://www.vishwashardwaresolution.com",
"tag": "pymongo",
"likes": 1520,
"comments": [
"All Hardware Problem solve",
]
}
allDocuments = [document1,document2,document3,document4,document5]
collection.insert_many(allDocuments)

print("Documents Inserted Successfully...!!!")

61291401- Ashik Ali (MCA-1 sem-2) Page 36


3.retrieves all the documents from the collection named mycol and arranges them in an easy-
to-read format

import pymongo

if __name__ == "__main__":
# print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
# print(client)

db = client['documentDB']
collection = db['myCol']

allDocs = collection.find()
print("Total Documents Found : ",collection.count_documents({}))
for item in allDocs:
print ("\nID :",item['_id'],
"\nTitle :",item['title'],
"\nDescription :",item['desc'],
"\nBy :",item['by'],
"\nURL :",item['url'],
"\nTag :",item['tag'],
"\nLikes :",item['likes'],
"\nComments :",item['comments'],)
print("\n---------------------------------------")

61291401- Ashik Ali (MCA-1 sem-2) Page 37


4. search documents having title as “MongoDB” and likes more than 1000

import pymongo

if __name__ == "__main__":
# print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
# print(client)

db = client['documentDB']
collection = db['myCol']

oneDoc = collection.find({'title': 'MongoDB'},{'likes':1, 'title':


1, '_id':0})
print("Search Specific Documents")
for item in oneDoc:
print(item)

61291401- Ashik Ali (MCA-1 sem-2) Page 38


5. delete documents having likes less than 50

import pymongo

if __name__ == "__main__":
# print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
# print(client)

db = client['documentDB']
collection = db['myCol']

lessthan50 = collection.find({'likes' : {'$lt': 50}})


print("Less than likes=50, documents ")
for item in lessthan50:
print("\nID :", item['_id'],
"\nTitle :", item['title'],
"\nDescription :", item['desc'],
"\nBy :", item['by'],
"\nURL :", item['url'],
"\nTag :", item['tag'],
"\nLikes :", item['likes'],
"\nComments :", item['comments'], )
print("\n---------------------------------------")

delete = collection.delete_many({'likes' : {'$lt': 50}})


print("\nDelete Records Successfully...!!!")

allDocs = collection.find()
print("\nRemaining Records after deletion")
for item in allDocs:
print("\nID :", item['_id'],
"\nTitle :", item['title'],

61291401- Ashik Ali (MCA-1 sem-2) Page 39


"\nDescription :", item['desc'],
"\nBy :", item['by'],
"\nURL :", item['url'],
"\nTag :", item['tag'],
"\nLikes :", item['likes'],
"\nComments :", item['comments'], )
print("\n---------------------------------------")

6.update the tags of all documents with “technology” keyword

import pymongo

if __name__ == "__main__":
# print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
# print(client)

db = client['documentDB']
collection = db['myCol']

prev = {"tag": "pymongo"}


nextt = {"$set" : {"tag":"technology"}}

collection.update_many(prev,nextt)
61291401- Ashik Ali (MCA-1 sem-2) Page 40
print("Update Successfully...!!!")
for item in collection.find():
print("\nID :", item['_id'],
"\nTitle :", item['title'],
"\nDescription :", item['desc'],
"\nBy :", item['by'],
"\nURL :", item['url'],
"\nTag :", item['tag'],
"\nLikes :", item['likes'],
"\nComments :", item['comments'], )
print("\n---------------------------------------")

Q. Suppose a client needs a database design for his blog/website. Website has
the following requirements: Every post has the unique title, description and
url. Every post can have one or more tags. Every post has the name of its
publisher and total number of likes. Every post has comments given by users

61291401- Ashik Ali (MCA-1 sem-2) Page 41


along with their name, message, datatime and likes. On each post, there can
be zero or more comments.
import pymongo
import datetime

if __name__ == "__main__":
# print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
# print(client)

db = client['my_Blog']
collection = db['col_blog']

x = datetime.datetime.now()
d = x.strftime("%c")
post1 = {
"_id": 1,
"title": "Fitness",
"description": "Exercise Increases \"feel good\" Hormones and N
eurotransmitters",
"by": "meenakshi jadhav",
"url": "https://wwww.mkfitness.com",
"tags": ['Fitness','Exercise','Running','Gym','Trainner'],
"likes": 500,
"comments": [
{
"user":'rupali jadhav',
"message": "Useful site for exercise",
"dateCreated": d,
"like": 10
},
{
"user":'rahul patil',
"message": "I read bolgs from past two month\'s and I try
all exercise, now I\'m very fit",
"dateCreated": d,
"like": 54
}
]
}

post2 = {
"_id": 2,
61291401- Ashik Ali (MCA-1 sem-2) Page 42
"title": "How to Create Bootstrap Login Form with PHP Validatio
n",
"description": "In this article I am going to explain the proce
ss of creating a bootstrap login form using twitter bootstrap.",
"by": "Pranil",
"url": "https://www.pranitsblogs.com",
"tags": ['Programming Blogs', 'UI','UX','Bootstrap','CSS'],
"likes": 249,
"comments": [
{
"user":'poonam pawar',
"message": "Excellent Keep up the good work.",
"dateCreated": d,
"like": 128
},
{
"user":'Vishal patil',
"message": "Very interesting",
"dateCreated": d,
"like": 25
}
]
}

post3 = {
"_id": 3,
"title": "The best gaming tablet you can get -
updated September 2021",
"description": "Mobile gaming is the future, and if you don’t
believe me, here are some numbers."
" In 2020, mobile games accounted for 57 percen
t of video gaming revenue worldwide and "
"reached a record 10.73 billion U.S. dollars in
the States.",
"by": "sonam pawar",
"url": "https://www.omiblogs.com",
"tags": ['Technology','Gadgets','Games','Mobiles'],
"likes": 90,
"comments": [
{
"user": 'Riya patil',
"message": "This is something special.",
"dateCreated": d,
"like": "24"

61291401- Ashik Ali (MCA-1 sem-2) Page 43


},
{
"user": 'Pranoti pawar',
"message": "That's coming along nicely.",
"dateCreated": d,
"like": 39
}
]
}

blogs = [post1,post2,post3]
#collection.insert_many(blogs)

print("Rp Blogs")
for item in collection.find():

print("\nID :", item['_id'],


"\nTitle :", item['title'],
"\nDescription :", item['description'],
"\nBy :", item['by'],
"\nURL :", item['url'],
"\nTags :", item['tags'],
"\nLikes :", item['likes'],
"\nComments :", item['comments'])
print("\n---------------------------------------")

61291401- Ashik Ali (MCA-1 sem-2) Page 44


12. Basic programs with NumPy as Array, Searching and Sorting, date & time
and String handling
Program-

NUMPY ARRAY OPERATIONS

ndim:

import numpy as np

a = np.array([(1,2,3),(4,5,6)])

print(a.ndim)

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 45


reshape()-

Program-

import numpy as np

a = np.array([(8,9,10),(11,12,13)])

print(a)

a=a.reshape(3,2)

print(a)

OUTPUT-

max/min()-
Program-

import numpy as np

a= np.array([1,2,3])

print(a.min())

print(a.max())

print(a.sum())

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 46


mathematical operation-
Program-

import numpy as np

x= np.array([(1,2,3),(3,4,5)])

y= np.array([(1,2,3),(3,4,5)])

print(x+y)

print(x-y)

print(x*y)

print(x/y)

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 47


Vertical & Horizontal Stacking

Program-

import numpy as np

x= np.array([(1,2,3),(3,4,5)])

y= np.array([(1,2,3),(3,4,5)])

print(np.vstack((x,y)))

print(np.hstack((x,y)))

OUTPUT-

NUMPY STRING
61291401- Ashik Ali (MCA-1 sem-2) Page 48
Numpy.lower-
Program-

import numpy as np

# converting to lowercase

print(np.char.lower(['PYTHON', 'FOR']))

# converting to lowercase

print(np.char.lower('PROGRAM'))

OUTPUT-

Numpy.split()-
Program-

import numpy as np

# splitting a string

print(np.char.split('welcome to python programming'))

# splitting a string

print(np.char.split('welcome, to, python', sep = ','))

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 49


numpy.isnumeric()-
PROGRAM

import numpy as np

# counting a substring

print(np.char.isnumeric('python'))

# counting a substring

print(np.char.isnumeric('12'))

OUTPUT-

numpy.find()-
Program-

word = 'welcome to python programming'

# returns first occurrence of Substring

result = word.find('python')

61291401- Ashik Ali (MCA-1 sem-2) Page 50


print ("Substring 'python' found at index:", result )

result = word.find('welcome')

print ("Substring 'welcome ' found at index:", result )

# How to use find()

if (word.find('ashik') != -1):

print ("Contains given substring ")

else:

print ("Doesn't contains given substring")

OUTPUT-

numpy.uppercase()-
Program-

# Python program to demonstrate the

# use of capitalize() function

# capitalize() first letter of string

61291401- Ashik Ali (MCA-1 sem-2) Page 51


# and make other letters lowercase

name = "welcome TO python programming"

print(name.capitalize())

# demonstration of individual words

# capitalization to generate camel case

name1 = "welcome"

name2 = "to"

name3 = "python"

name4 = "programming"

print(name1.capitalize() + name2.capitalize()+ name3.capitalize()


+name4.capitalize())

OUTPUT-

numpy date & time()-


Program-

import datetime

x = datetime.datetime.now()

61291401- Ashik Ali (MCA-1 sem-2) Page 52


print(x)

OUTPUT

PROGRAM

import datetime

x = datetime.datetime.now()

print(x.year)

print(x.strftime("%A"))

OUTPUT-

PROGRAM-

import datetime

x = datetime.datetime(2021, 9, 6)

print(x)

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 53


PROGRAM

import datetime

x = datetime.datetime(2021, 9, 7)

print(x.strftime("%B"))

OUTPUT-

13] Programs for series and data frames should be covered.

Q. Write a python program to demonstrate operations of series & data frames


Series Operation-

Program-

# importing pandas module

import pandas as pd

# creating a series

data = pd.Series([5, 2, 3,7], index=['a', 'b', 'c', 'd'])

# creating a series

data1 = pd.Series([1, 6, 4, 9], index=['a', 'b', 'd', 'e'])

print(data, "\n\n", data1)

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 54


1]add()-

2]sub()-

3]astype-

Program-

# Python program using astype

# to convert a datatype of series

# importing pandas module

import pandas as pd

# reading csv file from url

data = pd.read_csv("nba.csv")

61291401- Ashik Ali (MCA-1 sem-2) Page 55


# dropping null value columns to avoid errors

data.dropna(inplace = True)

# storing dtype before converting

before = data.dtypes

# converting dtypes using astype

data["Salary"]= data["Salary"].astype(int)

data["Number"]= data["Number"].astype(str)

# storing dtype after converting

after = data.dtypes

# printing to compare

print("BEFORE CONVERSION\n", before, "\n")

print("AFTER CONVERSION\n", after, "\n")

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 56


4]tolist()-

Program-

# Python program converting

# a series into list

# importing pandas module

import pandas as pd

# importing regex module

import re

# making data frame

data = pd.read_csv("nba.csv")

# removing null values to avoid errors

data.dropna(inplace = True)

# storing dtype before operation

61291401- Ashik Ali (MCA-1 sem-2) Page 57


dtype_before = type(data["Salary"])

# converting to list

salary_list = data["Salary"].tolist()

# storing dtype after operation

dtype_after = type(salary_list)

# printing dtype

print("Data type before converting = {}\nData type after converting = {}"

.format(dtype_before, dtype_after))

# displaying list

salary_list

OUTPUT-

DataFrame Operation-

1]list()-

# import pandas as pd

import pandas as pd

# list of strings

61291401- Ashik Ali (MCA-1 sem-2) Page 58


lst = ['Geeks', 'For', 'Geeks', 'is',

'portal', 'for', 'Geeks']

# Calling DataFrame constructor on list

df = pd.DataFrame(lst)

print(df)

OUTPUT-

2]dict to ndarray/list()-

# Python code demonstrate creating

# DataFrame from dict narray / lists

# By default addresses.

import pandas as pd

# initialise data of lists.

data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]}

# Create DataFrame

df = pd.DataFrame(data)

61291401- Ashik Ali (MCA-1 sem-2) Page 59


# Print the output.

print(df)

OUTPUT-

4] dictionary()-

Program-

# importing pandas as pd

import pandas as pd

# dictionary of lists

dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],

'degree': ["MBA", "BCA", "M.Tech", "MBA"],

'score':[90, 40, 80, 98]}

df = pd.DataFrame(dict)

print(df)

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 60


14] Programs to demonstrate data pre-processing and data handling with data
frame

Q. Read employee.csv file in dataframe emp and do following: Drop the


records of employees whose names are missing Replace the missing salaries
with mean of salaries Remove the columns with maximum missing values Fix
the type of joining-Date column to date
import pandas as pd

import numpy as np

df=pd.read_csv('employee.csv')

#Drop the records of employees whose names are missing

df2=df[df["Employee_name"].notnull()]

print(df2)

print("--------------------------------------------------------------------------------------------------------")

# Replace the missing salaries with mean of salaries

df["salary"].fillna((df["salary"].mean()),inplace=True)

print(df.to_string())

print("--------------------------------------------------------------------------------------------------------")

#Remove the columns with maximum missing values

df3=df.isnull().mean()

print(df3)

df5=df[df.columns[df.isnull().mean() < 0.5]]

print(df5)

print("--------------------------------------------------------------------------------------------------------")

# Fix the type of joining-Date column to date


61291401- Ashik Ali (MCA-1 sem-2) Page 61
df["e_hdate"]=pd.to_datetime(df['e_hdate'])

print(df.to_string())

OUTPUT-

Employee.csv

15] Program for data visualization should be covered.

Q. Read employee.csv file in dataframe emp and plot following:

Line graph to show the yearly hike in employees salaries

61291401- Ashik Ali (MCA-1 sem-2) Page 62


import pandas as pd

from matplotlib import pyplot as plt

df = pd.DataFrame({"Year" : [2014,2015,2016,2017,2018],

"Sales" : [2000, 3000, 4000, 3500, 6000]})

# plot line chart

plt.plot(df["Year"], df["Sales"])

plt.title("Simple Line Plot")

plt.xlabel('Year')

plt.ylabel('Sales')

plt.show()

OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 63


Scatter plot to show relationship between age and salary of employees

import matplotlib.pyplot as plt

import pandas as pd

import numpy as np

df=pd.read_csv('employee.csv')

plt.title("Age Vs Salary")

plt.xlabel("Salary")

plt.ylabel("Age")

plt.scatter(df.salary,df.age)

61291401- Ashik Ali (MCA-1 sem-2) Page 64


plt.show()

OUTPUT-

Histogram to show frequency of employee salaries under each bin(range)

import matplotlib.pyplot as plt

import pandas as pd

import numpy as np

df=pd.read_csv('employee.csv')

df.hist(column='salary',bins=7,grid=False, figsize=(8,4), color='#86bf91', rwidth=0.5)

plt.show()

61291401- Ashik Ali (MCA-1 sem-2) Page 65


OUTPUT-

61291401- Ashik Ali (MCA-1 sem-2) Page 66


61291401- Ashik Ali (MCA-1 sem-2) Page 67

You might also like