0% found this document useful (0 votes)
80 views16 pages

PRP PT2 Soln (Programs)

The document contains code snippets for multithreading, inheritance, exception handling, file handling, classes and objects, regular expressions, GUI programming and database connectivity in Python. Multiple questions related to these Python concepts are answered through code examples.

Uploaded by

radha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views16 pages

PRP PT2 Soln (Programs)

The document contains code snippets for multithreading, inheritance, exception handling, file handling, classes and objects, regular expressions, GUI programming and database connectivity in Python. Multiple questions related to these Python concepts are answered through code examples.

Uploaded by

radha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Q1.

from threading import *


l=Lock()
class leap:
def show(self,n,m):
for year in range(n,m):
l.acquire()
if (year % 400 == 0):
print(year,"Is a leap year")
elif (year % 4 == 0 and year % 100 != 0):
print(year,"Is a leap year")
l.release()
obj=leap()
t1=Thread(target=obj.show, args=(1700,1801))
t2=Thread(target=obj.show, args=(1801,1901))
t3=Thread(target=obj.show, args=(1901,2001))
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()

Q2.
class Student:
def __init__(self,id,name,sem):
self.id=id
self.name=name
self.sem=sem
class Test(Student):
def __init__(self,id,name,sem,mark1,mark2,mark3):
super().__init__(id,name,sem)
self.mark1=mark1
self.mark2=mark2
self.mark3=mark3
class Sports:
def __init__(self,position):
self.position=position
class Result(Test,Sports):
def __init__(self, id, name, sem, mark1, mark2,
mark3,position):

super().__init__(id, name, sem, mark1, mark2, mark3)


self.position=position
def display(self):
total=self.mark1+self.mark2+self.mark3
if self.position=="District":
total+=10
elif self.position=="State":
total+=15
elif self.position=="National":
total+=20
else:
total+=0
print("Student ID:",self.id)
print("Name:",self.name)
print("Semester:",self.sem)
print("Marks:",total)
s=Result(1,'Ram',4,80,90,100,"State")
s.display()

Q3.
class CustomException(Exception):
def __init__(self,msg):
self.msg=msg

id=int(input("Enter the id:"))


name=input("Enter the name:")
sem=int(input("Enter the semester:"))
city=input("Enter the city:")

if len(name)< 2:
raise CustomException("Name should be more than 2 or
more")
if sem<1 or sem>6:
raise CustomException("Semester should be between 1 or
6")
Q4.
class CustomException(Exception):
def __init__(self,msg):
self.msg=msg

title=input("Enter the title:")


author=input("Enter the author name:")
publisher=input("Enter the publisher:")
price=int(input("Enter the price:"))
qty=int(input("Enter the quantity:"))
country=input("Enter the country of publisher:")

if qty<20:
raise CustomException("Quantity should be greater than
20")
if country!="India":
raise CustomException("Country Should be India")

Q5.
bpay=int(input("Enter basic pay : "))
hra = 0.25*bpay
da = 0.65*bpay
ga = bpay + hra+da
# print(ga)
grade=input("Enter the grade : ")
if grade == 'A':
ga+=5000
elif grade == 'B':
ga+=4000
elif grade == 'C':
ga+=2300
elif grade =="D":
ga+=1100
else:
print("Enter valid grade")
print(ga)
Q6.
import re
date_regex = r'[(20)|(19)]\d{2}[/_]0[45][/_](0[1-
9]|[12]\d|3[01])'
text = "Some dates: 20220410, 2022/05/15, 2023_04_20, 2023-
05-25, 20240530, 1905/04/32"
matches = re.findall(date_regex, text)
for match in matches:
print(f"Date: {match}")

Q7.
import re
data = '''
5654321098
1234567890
9876543210
'''
items = re.finditer(r"[7-9]\d{9}",data)
for i in items:
print(i.group())

Q8.
import re
def validate_password(password):
# Check if password is at least 8 characters long
if len(password) < 8:
return False

# Check if password contains at least one uppercase


letter
if not re.search(r'[A-Z]', password):
return False

# Check if password contains at least one lowercase


letter
if not re.search(r'[a-z]', password):
return False

# Check if password contains at least one digit


if not re.search(r'\d', password):
return False
# Check if password contains at least one special
character
if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
return False

# If all conditions are met, the password is valid


return True

passwords = ["Aji1#der", "AbCD12", "KI342$&Ha"]

for password in passwords:


is_valid = validate_password(password)

if is_valid:
print(f"{password} is a valid password.")
else:
print(f"{password} is not a valid password.
source_file = 'PT2_20Programs/website.jpg'
destination_folder = './PT2_20Programs'
destination_file = destination_folder + '/copied_image.jpg'

with open(source_file, 'rb') as src:


with open(destination_file, 'wb') as dst:
dst.write(src.read())

if(destination_file):
print("Success")
Q9.
class Person:
def __init__(self,name,age,city):
self.name = name
self.age = age
self.city = city
class Student(Person):
def
__init__(self,name,age,city,id,semester,discipline,m1,m2,m3):
super().__init__(name,age,city)
self.id = id
self.semester = semester
self.discipline = discipline
self.m1 = m1
self.m2 = m2
self.m3 = m3
def totalMarks(self):
return self.m1+self.m2+self.m3
def displayInfo(self):
print(f"Name: {self.name}\nAge: {self.age}\nCity:
{self.city}\nID: {self.id}\nSemester:
{self.semester}\nDiscipline: {self.discipline}\nTotal Marks:
{self.totalMarks()}")
class Teacher(Person):
def __init__(self,name,age,city,hr_taught,rp_hr):
super().__init__(name,age,city)
self.hr_taught = hr_taught
self.rp_hr= rp_hr
def calSal(self):
if self.hr_taught>=40:
return self.hr_taught*(self.rp_hr*1.5)
else:
return self.hr_taught*self.rp_hr
def displayInfo(self):
print(f"Name: {self.name}\nAge: {self.age}\nCity:
{self.city}\nHours Taught: {self.hr_taught}\nRate per Hour:
{self.rp_hr}\nSalary: {self.calSal()}")

s = Student("Rahul",20,"Delhi",1,3,"CSE",90,80,70)
s.displayInfo()
t = Teacher("Mr. Sharma",45,"Delhi",50,1000)
t.displayInfo()
Q10.
import mysql.connector
import tkinter as tk
from tkinter import *
def calculate_average():
try:
name=(t1.get())
runs = int(t2.get())
nouts = int(t4.get())
ings= int(t3.get())
average = runs/(ings-nouts)
average=round(average,2)
t5.set(average)

conn=mysql.connector.connect(host="localhost",u
ser="root",password="",database="Q11db")
cur=conn.cursor()
sql="INSERT INTO Q11tb
(name,runs,inings,not_out) VALUES(%s,%s,%s,%s)"
val=(name,runs,ings,nouts)
cur.execute(sql,val)
conn.commit()

t1.set("")
t2.set("")
t3.set("")
t4.set("")
except ValueError:
print("Enter the valid inputs")

root=tk.Tk()
root.title("Batting Average Calculator")

t1=StringVar()
t2=StringVar()
t3=StringVar()
t4=StringVar()
t5=StringVar()
name_label = tk.Label(root,text="Name:")
name_label.place(x=50,y=50)
name_entry = tk.Entry(root,textvariable=t1)
name_entry.place(x=90,y=50)

run_label = tk.Label(root,text="Runs:")
run_label.place(x=50,y=90)
run_entry = tk.Entry(root,textvariable=t2)
run_entry.place(x=90,y=90)

ing_label = tk.Label(root,text="Inings:")
ing_label.place(x=50,y=130)
ing_entry = tk.Entry(root,textvariable=t3)
ing_entry.place(x=90,y=130)

nouts_label = tk.Label(root,text="Not Outs:")


nouts_label.place(x=50,y=170)
nouts_entry = tk.Entry(root,textvariable=t4)
nouts_entry.place(x=105,y=170)

calculate_button = tk.Button(root, text="Calculate


Average", command=calculate_average)
calculate_button.place(x=50,y=250)

display_entry=tk.Entry(root,text="Average",textvariable
=t5)
display_entry.place(x=50,y=210)

root.mainloop()
Q11.
import re
Data='''
jhjhgure.jhsfdjsfg2AODAO.EDU
[email protected]
[email protected]
'''
pattern=re.compile(r'.+@\w+\.\w+')
checking=pattern.finditer(Data)
for i in checking:
print(i.group())
Q12
import re
Data = '''
ab abab abab
Mr. Vishal
Mr Hitesh
Ms. Komal
Mrs. Priyanka
Mr. A
'''
pattern = re.finditer(r'Mr\.?\s[A-Za-z]\w*',Data)
for i in pattern:
print(i.group())
Q14.
import mysql.connector
try:
con = mysql.connector.connect(
host="localhost",
user="root",
password="",
)
print("Connection Established Successfully")
c1 = con.cursor()
c1.execute("create database test30")
c1.execute("show databases")
dbs=c1.fetchall()
for x in dbs:
print(x)
except:
print("Connection Error")
Q15.
import mysql.connector
from tkinter import *

def submit():
try:
mydb = mysql.connector.connect(host="localhost",
user="root", password="", database="q15")
c1 = mydb.cursor()
sql = "INSERT INTO login VALUES (%s, %s, %s, %s, %s,
%s, %s, %s)"
v1 = e1.get()
v2 = e2.get()
v3 = e3.get()
v4 = e4.get()
v5 = e5.get()
v6 = e6.get()
v7 = e7.get()
v8 = e8.get()

c1.execute(sql, (v1, v2, v3, v4, v5, v6, v7, v8))


mydb.commit()
print("Data inserted successfully")
mydb.close()
except mysql.connector.Error as err:
print(f"Error: {err}")

def clear():
e1.delete(0,END)
e2.delete(0,END)
e3.delete(0,END)
e4.delete(0,END)
e5.delete(0,END)
e6.delete(0,END)
e7.delete(0,END)
e8.delete(0,END)
root = Tk()
root.title("Address Entry Form")
root.geometry('500x500')

fname = Label(root, text="First Name:")


fname.grid(row=0, column=0)
e1 = Entry(root, width=50)
e1.grid(row=0, column=1)

lname = Label(root, text="Last Name:")


lname.grid(row=1, column=0)
e2 = Entry(root, width=50)
e2.grid(row=1, column=1)

add1 = Label(root, text="Address Line 1:")


add1.grid(row=2, column=0)
e3 = Entry(root, width=50)
e3.grid(row=2, column=1)

add2 = Label(root, text="Address Line 2:")


add2.grid(row=3, column=0)
e4 = Entry(root, width=50)
e4.grid(row=3, column=1)

city = Label(root, text="City:")


city.grid(row=4, column=0)
e5 = Entry(root, width=50)
e5.grid(row=4, column=1)

state = Label(root, text="State/Province:")


state.grid(row=5, column=0)
e6 = Entry(root, width=50)
e6.grid(row=5, column=1)

code = Label(root, text="Postal Code:")


code.grid(row=6, column=0)
e7 = Entry(root, width=50)
e7.grid(row=6, column=1)

country = Label(root, text="Country:")


country.grid(row=7, column=0)
e8 = Entry(root, width=50)
e8.grid(row=7, column=1)

btn1 = Button(root, text="Clear",command=clear)


btn1.grid(row=8, column=1)
btn2 = Button(root, text="Submit", command=submit)
btn2.grid(row=9, column=1)

root.mainloop()
Q16
import mysql.connector
from tkinter import *

def login():
try:
mydb = mysql.connector.connect(host="localhost",
user="root", password="", database="q15")
c1 = mydb.cursor()
v1=e1.get()
v2=e2.get()
sql = "SELECT * FROM validation WHERE username = %s
AND password = %s"
c1.execute(sql,(v1,v2))
print("SUCCESS")
except mysql.connector.Error as err:
print(f"Error: {err}")

root = Tk()
root.title("Login Page")
root.geometry('500x500')

uname = Label(root, text="Username-")


uname.grid(row=0, column=0)
e1 = Entry(root, width=30)
e1.grid(row=0, column=1)

password = Label(root, text="Password-")


password.grid(row=1, column=0)
e2 = Entry(root, width=30)
e2.grid(row=1, column=1)

btn1=Button(root,text="Login",command=login).grid(row=5,colum
n=0)
root.mainloop()
Q17.
class Vehicle:
def __init__(self,id,pCapacity):
self.id = id
self.pCapacity = pCapacity

class Fueled(Vehicle):
def __init__(self,id,pCapacity,fuelType,fuelCapacity):
super().__init__(id,pCapacity)
self.fuelType = fuelType
self.fuelCapacity = fuelCapacity

class NonFueled(Vehicle):
def __init__(self,id,pCapacity):
super().__init__(id,pCapacity)

class Car(Fueled):
def
__init__(self,id,pCapacity,fuelType,fuelCapacity,brand,model,year):
super().__init__(id,pCapacity,fuelType,fuelCapacity)
self.brand = brand
self.model = model
self.year = year
def displayInfo(self):
print(f"ID: {self.id}\nPassenger Capacity:
{self.pCapacity}\nFuel Type: {self.fuelType}\nFuel Capacity:
{self.fuelCapacity}\nBrand: {self.brand}\nModel: {self.model}\nYear:
{self.year}")

class Bicycle(NonFueled):
def __init__(self,id,pCapacity,brand,model,year):
super().__init__(id,pCapacity)
self.brand = brand
self.model = model
self.year = year

def displayInfo(self):
print(f"ID: {self.id}\nPassenger Capacity:
{self.pCapacity}\nBrand: {self.brand}\nModel: {self.model}\nYear:
{self.year}")

c = Car(1,5,"Petrol",50,"Maruti","Swift",2020)
c.displayInfo()
print("\n")
b = Bicycle(2,1,"Firefox","Road Runner",2020)
b.displayInfo()
Q18.
class Person:
def __init__(self,name,age,city):
self.name=name
self.age=age
self.city=city

class Employee(Person):
def __init__(self,name,age,city,id,designation,salary):
super().__init__(name,age,city)
self.id=id
self.designation=designation
self.salary=salary

class Customer(Person):
def __init__(self,name,age,city,cid,cphone):
super().__init__(name,age,city)
self.cid=cid
self.cphone=cphone

class Manager(Employee):
def __init__(self,name,age,city,id,designation,salary,dept):
super().__init__(name,age,city,id,designation,salary)
self.dept=dept
def display(self):
print(f"Name: {self.name}\nAge: {self.age}\nCity:
{self.city}\nId: {self.id}\nDesignation:
{self.designation}\nSalary: {self.salary}\nDepartment:
{self.dept}")

class Developer(Employee):
def __init__(self,name,age,city,id,designation,salary,tech):
super().__init__(name,age,city,id,designation,salary)
self.tech=tech
def display(self):
print(f"Name: {self.name}\nAge: {self.age}\nCity:
{self.city}\nId: {self.id}\nDesignation:
{self.designation}\nSalary: {self.salary}\nTechnology:
{self.tech}")

m=Manager("Ramesh",50,"Mumbai",1,"Manager",500000,"HR")
m.display()
print("\n")
d=Developer("Mohan",25,"Bangalore",2,"Developer",50000,"FULL
STACK")
m.display()
Q19.
import tkinter as tk
import mysql.connector

# Connect to MySQL database


mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="pythondb"
)
mycursor = mydb.cursor()

# Create Tkinter window


window = tk.Tk()
window.title("Electricity Bill Calculator")

# Create labels and textboxes


units_label = tk.Label(window, text="Enter units consumed:")
units_label.grid(row=0, column=0, padx=10, pady=10)
units_entry = tk.Entry(window, width=10)
units_entry.grid(row=0, column=1, padx=10, pady=10)

bill_label = tk.Label(window, text="Calculated bill:")


bill_label.grid(row=1, column=0, padx=10, pady=10)
bill_entry = tk.Entry(window, width=10)
bill_entry.grid(row=1, column=1, padx=10, pady=10)

# Create function to calculate bill


def calculate_bill():
units = int(units_entry.get())
if units <= 180:
charge = 40 + 0.6 * units
elif units <= 240:
charge = 80 + 0.8 * (units - 180) + 40 + 0.6 * 180
elif units <= 300:
charge = 120 + 0.9 * (units - 240) + 80 + 0.8 * 60
else:
charge = 160 + (units - 300) + 120 + 0.9 * 60
bill_entry.delete(0, tk.END)
bill_entry.insert(0, charge)

# Create "Calculate" button


calculate_button = tk.Button(window, text="Calculate",
command=calculate_bill)
calculate_button.grid(row=2, column=0, columnspan=2, padx=10, pady=10)

# Create function to store record into MySQL table


def store_record():
units = int(units_entry.get())
bill = float(bill_entry.get())
sql = "INSERT INTO consumers (units, bill) VALUES (%s, %s)"
val = (units, bill)
mycursor.execute(sql, val)
mydb.commit()

# Create "Store Record" button


store_button = tk.Button(window, text="Store Record",
command=store_record)
store_button.grid(row=3, column=0, columnspan=2, padx=10, pady=10)

# Start Tkinter event loop


window.mainloop()

Q20.
def matrix_addition(matrix1,matrix2):
result=[]
for i in range(len(matrix1)):
row=[]
for j in range(len(matrix1[0])):
row.append(matrix1[i][j]+matrix2[i][j])
result.append(row)
return result

def display_matrix(matrix):
for row in matrix:
print(row)

matrix1 = [[1,2],[3,4]]
matrix2 = [[5,6],[7,8]]

result = matrix_addition(matrix1,matrix2)

print("Result of addition : ")


display_matrix(result)
#done

You might also like