Python Program (Journal)
Python Program (Journal)
JOURNAL
MCA-1(SEM-2)
Date: 11/09/2021
CERTIFICATE
Q. In this project, you’ll learn how to create 2 random teams from a list of players
Program-
players = []
players = file.read().splitlines()
print('Players:', players)
teamNames = []
teamA = []
teamB = []
playerA = choice(players)
teamA.append(playerA)
players.remove(playerA)
if players == []:
break
playerB = choice(players)
teamB.append(playerB)
players.remove(playerB)
teamNameA = choice(teamNames)
teamNames.remove(teamNameA)
teamNames.remove(teamNameB)
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 dequeue(self):
return self.items.pop(0)
q = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('view')
print('quit')
operation = do[0].strip().lower()
if operation == 'enqueue':
q.enqueue(int(do[1]))
if q.is_empty():
print('Queue is empty.')
else:
elif operation=='view':
if q.is_empty():
else:
break
OUTPUT-
Program-
# initialize sum
sum = 0
temp = num
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
else:
OUTPUT-
def recursive_list_sum(data_list):
total = 0
if type(element) == type([]):
return total
OUTPUT-
Q. In this project, you are passing the secret message (encrypted) to your colleague, your
colleague know key to decrypt it
Program-
key = Fernet.generate_key()
fernet = Fernet(key)
encMessage = fernet.encrypt(message.encode())
decMessage = fernet.decrypt(encMessage).decode()
OUTPUT-
import random
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
temp = random.sample(all,length)
password = "".join(temp)
print(password)
OUTPUT-
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:
dept=""
salary=0.0
def displaydata(self):
try:
print("=========================================")
raise ValueError
else:
except ValueError:
print("=============================================")
# for i in range(n):
emp1=Employe()
emp1.displaydata()
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"}
discounts={
"item1":"20",
"item2":"15",
"item3":"10"
class Shop(Discount_item):
Customer_name=""
Item_name=[]
selected_item=[]
selected_Price=[]
selected_dis=[]
def bill(self):
for n in self.Item_name:
if n == value:
self.selected_item.append(key)
# print(self.selected_item)
for i in self.selected_item:
if i == key:
self.selected_Price.append(value)
# print(self.selected_Price)
for i in self.selected_item:
self.selected_dis.append(value)
# print(self.selected_dis)
print("================BILL============")
for i in self.Item_name:
print(i)
sum=0
for i in self.selected_Price:
sum+=int(i)
dis=0
for i in self.selected_dis:
dis+=int(i)
print("=========================================")
def menu(self):
print("================Menu===================")
print("Item 1) cake Rs650 \n Item 2) brownie Rs300 \n Item 3) choco lava Rs200 ")
s1=Shop()#Object Created
# for i in range(n):
s1.bill()
OUTPUT-
Program-
class Employee:
self.id = id
self.name = name
self.dept = dept
self.salary = salary
self.raiseSalary()
def raiseSalary(self):
6]. Programs for parsing of data, validations like Password, email, URL, etc.
import re
OUTPUT-
flag = 0
while True:
if (len(password)<8):
flag = -1
break
flag = -1
break
flag = -1
break
flag = -1
break
flag = -1
break
flag = -1
break
else:
flag = 0
break
if flag ==-1:
OUTPUT-
8]. Programs covering all the aspects of Exception handling, user defined
exception, Multithreading should be covered.
class Bank_Account:
def __init__(self):
self.balance=0
def deposit(self):
self.balance += amount
def withdraw(self):
if self.balance>=amount:
self.balance-=amount
else:
def display(self):
# Driver code
s = Bank_Account()
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.close()
def display(self):
file=open("emp.txt","r")
print(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
file.close()
# print("Hello")
self.simple_str+=anothereach
# print(self.simple_str)
print(self.simple_str)
self.simple_str+=""
file2.close()
file =open("./emp.txt","w")
file.write("")
file.close
f1= File1()
print("=================person",i+1,"========================")
print("================================================")
f1.addData(name,age,salary)
f1.display()
Output-
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("\n")
file2.close()
file1.close()
OUTPUT-
sal=open("salraise.txt","a")
emps=[]
emps=eps.split()
print(emps)
if int(emps[3])<40000:
emps[3]=int(emps[3])+(int(emps[3])*0.1)
#emp.close()
sal.close()
OUTPUT-
if __name__ == "__main__":
print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
print(client)
db = client['documentDB']
collection = db['myCol']
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"
]
}
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)
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---------------------------------------")
import pymongo
if __name__ == "__main__":
# print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
# print(client)
db = client['documentDB']
collection = db['myCol']
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("\nRemaining Records after deletion")
for item in allDocs:
print("\nID :", item['_id'],
"\nTitle :", item['title'],
import pymongo
if __name__ == "__main__":
# print("Welcome to pyMongo")
client = pymongo.MongoClient("mongodb://localhost:27017")
# print(client)
db = client['documentDB']
collection = db['myCol']
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
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"
blogs = [post1,post2,post3]
#collection.insert_many(blogs)
print("Rp Blogs")
for item in collection.find():
ndim:
import numpy as np
a = np.array([(1,2,3),(4,5,6)])
print(a.ndim)
OUTPUT-
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-
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-
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
# splitting a string
OUTPUT-
import numpy as np
# counting a substring
print(np.char.isnumeric('python'))
# counting a substring
print(np.char.isnumeric('12'))
OUTPUT-
numpy.find()-
Program-
result = word.find('python')
result = word.find('welcome')
if (word.find('ashik') != -1):
else:
OUTPUT-
numpy.uppercase()-
Program-
print(name.capitalize())
name1 = "welcome"
name2 = "to"
name3 = "python"
name4 = "programming"
OUTPUT-
import datetime
x = datetime.datetime.now()
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-
import datetime
x = datetime.datetime(2021, 9, 7)
print(x.strftime("%B"))
OUTPUT-
Program-
import pandas as pd
# creating a series
# creating a series
OUTPUT-
2]sub()-
3]astype-
Program-
import pandas as pd
data = pd.read_csv("nba.csv")
data.dropna(inplace = True)
before = data.dtypes
data["Salary"]= data["Salary"].astype(int)
data["Number"]= data["Number"].astype(str)
after = data.dtypes
# printing to compare
OUTPUT-
Program-
import pandas as pd
import re
data = pd.read_csv("nba.csv")
data.dropna(inplace = True)
# converting to list
salary_list = data["Salary"].tolist()
dtype_after = type(salary_list)
# printing dtype
.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
df = pd.DataFrame(lst)
print(df)
OUTPUT-
2]dict to ndarray/list()-
# By default addresses.
import pandas as pd
# Create DataFrame
df = pd.DataFrame(data)
print(df)
OUTPUT-
4] dictionary()-
Program-
# importing pandas as pd
import pandas as pd
# dictionary of lists
df = pd.DataFrame(dict)
print(df)
OUTPUT-
import numpy as np
df=pd.read_csv('employee.csv')
df2=df[df["Employee_name"].notnull()]
print(df2)
print("--------------------------------------------------------------------------------------------------------")
df["salary"].fillna((df["salary"].mean()),inplace=True)
print(df.to_string())
print("--------------------------------------------------------------------------------------------------------")
df3=df.isnull().mean()
print(df3)
print(df5)
print("--------------------------------------------------------------------------------------------------------")
print(df.to_string())
OUTPUT-
Employee.csv
df = pd.DataFrame({"Year" : [2014,2015,2016,2017,2018],
plt.plot(df["Year"], df["Sales"])
plt.xlabel('Year')
plt.ylabel('Sales')
plt.show()
OUTPUT-
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)
OUTPUT-
import pandas as pd
import numpy as np
df=pd.read_csv('employee.csv')
plt.show()