0% found this document useful (0 votes)
6 views15 pages

Python Programming

Python programming

Uploaded by

mrinal19
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views15 pages

Python Programming

Python programming

Uploaded by

mrinal19
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Experiment -1

Write python program for calculator and store result in dictionary , in dictionary when user
selects add then key add will be added, when subtract is selected then key subtract is added
and output is stored in list tin appending mode if next time add is again selected.

Source Code:-

def add(x, y):return x + y


def subtract(x, y):return x - y
def multiply(x, y):return x * y
def divide(x, y):return x / y
print("Select operation.")print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide")
while True:
choice = input("Enter choice(1/2/3/4): ")if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: ")) num2 =
float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
next_calculation = input("Let's do next calculation? (yes/no): ")if next_calculation == "no":
break
else:
print("Invalid Input")

OUTPUT-
Experiment-2

Write Python program for check URL is present in string or not. import re

def Find(string):

regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-
z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()
<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
url = re.findall(regex,string)return [x[0] for x in url]

# Driver Code string = 'My Profile:


https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles inthe portal of
https://www.geeksforgeeks.org/'
print("Urls: ", Find(string))

OUTPUT-
Experiment-3

Write a program to implement single and multiple inheritance using python programming.
Source Code:-

Single Inheritance using Python Example:


class Parent_class(object):
def __init__(self, name, id):
self.name = name
self.id = id
def Employee_Details(self):
return self.id , self.name
def Employee_check(self):
if self.id > 500000:
return " Valid Employee "
else:
return " Invalid Employee "
class Child_class(Parent_class):
def End(self):
print(" END OF PROGRAM " )
Employee1 = Parent_class("Employee1" , 600445)
print(Employee1.Employee_Details(), Employee1.Employee_check() )
Employee2 = Child_class( "Employee2" , 198754)
print(Employee2.Employee_Details(), Employee2.Employee_check() )
Employee2.End()

OUTPUT:

Multiple Inheritance example:

INPUT:

class A:
def A(self):
print('This is class A.')
class B:
def B(self):
print('This is class B.')
class C(A,B):
def C(self):
print('This is class C which inherits features of both classes A and B.')
o = C()
o.A()
o.B()
o.C()

OUTPUT:
Experiment-4
Write Python program for addition of two matrix nested loop.
Source Code:-

X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)

Output-
Experiment-5
Write a python program for addition of two matrix using numpy and zip().

Source Code:-

import numpy as np
P = np.array([[1, 2], [3, 4]])
Q = np.array([[4, 5], [6, 7]])
print("Elements of the first matrix")
print(P)
print("Elements of the second matrix")
print(Q)
print("The sum of the two matrices is")
print(np.add(P, Q))

Output:-

Elements of the first matrix


[[1 2]
[3 4]]
Elements of the second matrix
[[4 5]
[6 7]]
The sum of the two matrices is
[[ 5 7]
[ 9 11]]
Using Zip()
X = [[1,2,3],
[4 ,0,6],
[7 ,8,9]]
Y = [[9,4, 7],
[6,5,2],
[3,2,6]]
result1= [map(sum, zip(*t)) for t in zip(X, Y)]
print(result)
Experiment- 6
Write a python program to find transpose of a matrix.
Source Code:-
A = [[5, 4, 3],
[2, 4, 6],
[4, 7, 9],
[8, 1, 3]]
transResult = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
for a in range(len(A)):
for b in range(len(A[0])):
transResult[b][a] = A[a][b]
print("The transpose of matrix A is: ")
for res in transResult:
print(res)

Output-
Experiment- 7
Write a python program to Implement Nested dictionary concept.
Source Code:-

Dict = { 'Dict1': { },
'Dict2': { }}
print("Nested dictionary 1-")
print(Dict)
Dict = { 'Dict1': {'name': 'Ali', 'age': '19'},
'Dict2': {'name': 'Bob', 'age': '25'}}
print("\nNested dictionary 2-")
print(Dict)
Dict = { 'Dict1': {1: 'G', 2: 'F', 3: 'G'},
'Dict2': {'Name': 'Geeks', 1: [1, 2]} }
print("\nNested dictionary 3-")
print(Dict)

Output-
Experiment-8
Write python program for implement operator overloading for + operator that can work on string
as well as list and dictionary.
class A:
def __init__(self, a):
self.a = a
def __add__(self, o):
return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")
print(ob1 + ob2)
print(ob3 + ob4)
# Actual working when Binary Operator is used.
print(A.__add__(ob1 , ob2))
print(A.__add__(ob3,ob4))
#And can also be Understand as :
print(ob1.__add__(ob2))
print(ob3.__add__(ob4))

Output-
Experiment- 9
Write Python program to read json file and print data on console.
Source Code:-

import json
employee ='{"id":"09", "name": "Kanhaiya", "department":"MCA"}'
employee_dict = json.loads(employee)
print(employee_dict)
print(employee_dict['name'])

Output-
Experiment-10
Python program for Binary Search (Recursive and Iterative).
Source Code:-

def binary_search(arr, low, high, x):


if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
arr = [ 2, 3, 4, 10, 40 ]
x = 10
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")

Output-
Experimet-11
Implement data-abstraction in python, try to create object of abstract class.
Source Code:-

from abc import ABC, abstractmethod


class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
class Triangle(Polygon):
def noofsides(self):
print("I have 3 sides")
class Pentagon(Polygon):
def noofsides(self):
print("I have 5 sides")
class Hexagon(Polygon):
def noofsides(self):
print("I have 6 sides")
class Quadrilateral(Polygon):
def noofsides(self):
print("I have 4 sides")
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()

Output-
Experiment-12
Write python program to maintain student’s database in a file that is student name, admission
no, subjects, marks. Initially there is only 3 subjects and 3 marks, further there 2 more subjects
are added , update the file
Source Code:-

class Student:
marks = []
def getData(self, rn, name, m1, m2, m3):
Student.rn = rn
Student.name = name
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)
def displayData(self):
print ("Roll Number is: ", Student.rn)
print ("Name is: ", Student.name)
print ("Marks in subject 1: ", Student.marks[0])
print ("Marks in subject 2: ", Student.marks[1])
print ("Marks in subject 3: ", Student.marks[2])
print ("Marks are: ", Student.marks)
print ("Total Marks are: ", self.total())
print ("Average Marks are: ", self.average())
def total(self):
return (Student.marks[0] + Student.marks[1] +Student.marks[2])
def average(self):
return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)
r = int (input("Enter the roll number: "))
name = input("Enter the name: ")
m1 = int (input("Enter the marks in the first subject: "))
m2 = int (input("Enter the marks in the second subject: "))
m3 = int (input("Enter the marks in the third subject: "))
s1 = Student()
s1.getData(r, name, m1, m2, m3)
s1.displayData()

Output-
Experiment-13
Python code to remove duplicate elements
Source Code:-

def Remove(duplicate):
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print(Remove(duplicate))

Output-
Experiment-14
Implement method overloading for variable number of argument, suppose for addition of two
numbers , addition of 3 numbers, ……addition of 5 numbers, same function will take care of
result.
Source Code:-

def add(datatype, *args):


if datatype == 'int':
answer = 0
if datatype == 'str':
answer = ''
for x in args:
answer = answer + x
print(answer)
add('int', 5, 6)
add('str', 'Hi ', 'Geeks')

Output-
Experiement-15
Write python program for design website login page, register page, student-detail page, library-
detail page.
Source Code:-

import tkinter as tk
import mysql.connector
from tkinter import *
def submitact():
user = Username.get()
passw = password.get()
print(f"The name entered by you is {user} {passw}")
logintodb(user, passw)
def logintodb(user, passw):
if passw:
db = mysql.connector.connect(host ="localhost",user = user,password = passw,db ="College")
cursor = db.cursor()
else:
db = mysql.connector.connect(host ="localhost",user = user,db ="College")
cursor = db.cursor()
savequery = "select * from STUDENT"
try:
cursor.execute(savequery)
myresult = cursor.fetchall()
for x in myresult:
print(x)
print("Query Executed successfully")
except:
db.rollback()
print("Error occurred")
root = tk.Tk()
root.geometry("300x300")
root.title("DBMS Login Page")
# Defining the first row
lblfrstrow = tk.Label(root, text ="Username -", )
lblfrstrow.place(x = 50, y = 20)
Username = tk.Entry(root, width = 35)
Username.place(x = 150, y = 20, width = 100)
lblsecrow = tk.Label(root, text ="Password -")
lblsecrow.place(x = 50, y = 50)
password = tk.Entry(root, width = 35)
password.place(x = 150, y = 50, width = 100)
submitbtn = tk.Button(root, text ="Login",
bg ='blue', command = submitact)
submitbtn.place(x = 150, y = 135, width = 55)
root.mainloop()

Output-

You might also like