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

Python Programs for Various Concepts

Python programming

Uploaded by

mrinal19
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)
7 views15 pages

Python Programs for Various Concepts

Python programming

Uploaded by

mrinal19
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

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("[Link]") print("[Link]") print("[Link]") print("[Link]")
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 = [Link](regex,string)return [x[0] for x in url]

# Driver Code string = 'My Profile:


[Link] inthe portal of
[Link]
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):
[Link] = name
[Link] = id
def Employee_Details(self):
return [Link] , [Link]
def Employee_check(self):
if [Link] > 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() )
[Link]()

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 = [Link]([[1, 2], [3, 4]])
Q = [Link]([[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([Link](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 = [Link](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()
[Link]()
K = Quadrilateral()
[Link]()
R = Pentagon()
[Link]()
K = Hexagon()
[Link]()

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):
[Link] = rn
[Link] = name
[Link](m1)
[Link](m2)
[Link](m3)
def displayData(self):
print ("Roll Number is: ", [Link])
print ("Name is: ", [Link])
print ("Marks in subject 1: ", [Link][0])
print ("Marks in subject 2: ", [Link][1])
print ("Marks in subject 3: ", [Link][2])
print ("Marks are: ", [Link])
print ("Total Marks are: ", [Link]())
print ("Average Marks are: ", [Link]())
def total(self):
return ([Link][0] + [Link][1] +[Link][2])
def average(self):
return (([Link][0] + [Link][1] +[Link][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()
[Link](r, name, m1, m2, m3)
[Link]()

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 [Link]
from tkinter import *
def submitact():
user = [Link]()
passw = [Link]()
print(f"The name entered by you is {user} {passw}")
logintodb(user, passw)
def logintodb(user, passw):
if passw:
db = [Link](host ="localhost",user = user,password = passw,db ="College")
cursor = [Link]()
else:
db = [Link](host ="localhost",user = user,db ="College")
cursor = [Link]()
savequery = "select * from STUDENT"
try:
[Link](savequery)
myresult = [Link]()
for x in myresult:
print(x)
print("Query Executed successfully")
except:
[Link]()
print("Error occurred")
root = [Link]()
[Link]("300x300")
[Link]("DBMS Login Page")
# Defining the first row
lblfrstrow = [Link](root, text ="Username -", )
[Link](x = 50, y = 20)
Username = [Link](root, width = 35)
[Link](x = 150, y = 20, width = 100)
lblsecrow = [Link](root, text ="Password -")
[Link](x = 50, y = 50)
password = [Link](root, width = 35)
[Link](x = 150, y = 50, width = 100)
submitbtn = [Link](root, text ="Login",
bg ='blue', command = submitact)
[Link](x = 150, y = 135, width = 55)
[Link]()

Output-

Common questions

Powered by AI

Data abstraction in Python using abstract classes provides a way to define essential methods without implementing them, ensuring that derived classes must fulfill certain behaviors, leading to a consistent interface across implementations. This approach supports design flexibility and enforces certain structural contracts on subclasses. However, challenges include the need for careful design to ensure all potential use cases are accommodated in the abstract definitions. Additionally, the abstract class might not anticipate future changes in requirements, potentially leading to extensive refactoring in subclasses .

Multiple inheritance allows a class to inherit from more than one base class, enabling the new class to utilize properties and methods of multiple parent classes, fostering code reuse and extensibility. It benefits scenarios where a class needs to mimic the behaviors of multiple domains or functionalities. However, it can introduce complexity, such as ambiguity arising from the 'diamond problem' where two parent classes inherit from a common ancestor. This can lead to conflicts in method resolution if not managed properly using Python's Method Resolution Order (MRO).

Method overloading in Python, as shown in the experiment, allows a function to adapt its behavior to different numbers of input arguments. Although Python does not natively support method overloading like some other languages, similar functionality can be achieved using variable length arguments (*args and **kwargs). In the addition experiment, this is implemented by defining a single function that takes a data type and a variable number of arguments, computing the sum of arguments based on the specified type (integer or string). This design provides a flexible mechanism to handle different input configurations without redundant code .

Using JSON for storing and retrieving structured data in Python offers benefits such as human-readable syntax, ease of use, and compatibility with web technologies, facilitating data interchange between server and client-side applications. In the reviewed experiments, JSON allows structured data representations that can easily be parsed into Python dictionaries for manipulation. However, limitations include the potential for performance bottlenecks with large datasets due to its text format and the lack of support for more complex data types (such as custom objects) without additional encoding/decoding steps .

Using nested loops for matrix transposition involves explicitly iterating over rows and columns and swapping indices to transform rows into columns, which is simple but becomes cumbersome with larger matrices. In contrast, libraries like Numpy offer built-in functions such as `numpy.transpose()` that execute these operations more efficiently and with significantly less code, leveraging optimized C and Fortran algorithms under the hood. These functions allow for faster execution and greater clarity and maintainability, especially when dealing with multidimensional arrays .

Maintaining and updating a student database file in Python involves structuring the `Student` class to hold student data and manage operations such as adding and updating entries. Initially, subjects and marks are entered into the database where a combination of class attributes and methods store and display them. When adding new subjects, methods would append each new subject and its corresponding mark to the current list, updating both the file and the corresponding data structures in the current session. Proper file handling ensures data persistence across uses .

Using traditional nested loops for matrix addition involves iterating over each element, which is straightforward but can become verbose and error-prone with larger matrices. It provides clear control over each step but lacks efficiency. Using the Numpy library functions, such as `np.add()`, significantly simplifies the code by allowing vectorized operations that are more computationally efficient and easier to read and maintain. The Numpy method abstracts the loop operations, resulting in cleaner and more concise code, which often translates to better performance due to optimizations in the underlying libraries .

Using dictionaries in Python to store calculated results allows for an organized way to map specific operations to their results, ensuring that every operation has a corresponding, easily retrievable key. This facilitates repeated operations because each time an operation is performed (such as addition or subtraction), the result can be appended to a list associated with the operation's key. This setup efficiently allows future reference to past calculated results and enhances data manipulation and retrieval .

Operator overloading for the '+' operator allows a class to define its own behavior for data operations depending on its data. This enables the same '+' operator to be used with integers to perform arithmetic additions, or with strings to concatenate them. By defining a custom `__add__` method, the class can handle the operation based on object type, thus enhancing flexibility and extending functionality to more complex data types like strings or lists .

The URL detection process in Python uses regular expressions (regex) to scan text strings for URL patterns. The provided regex pattern identifies URLs by looking for common URL schemes (like 'http' or 'www'), domain names, paths, and optional query components. It matches on typical URL structures, including those with special characters and subdomains, ensuring that it captures a wide range of valid URLs. This allows the regex function `findall()` to iterate over the text and return any matching URLs, enabling automated URL extraction with high accuracy .

You might also like