0% found this document useful (0 votes)
19 views

Python Programs Final

This experiment aims to study basic data types, loops, control flow statements and decorators in Python. The document outlines 14 experiments covering print statements, data types, operators, input/output, conditional statements, loops, functions, decorators, iterators and generators. The experiments involve writing Python code to perform tasks like addition, comparison, type identification, looping, nested conditional logic and applying decorators.

Uploaded by

Taran Kaur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Python Programs Final

This experiment aims to study basic data types, loops, control flow statements and decorators in Python. The document outlines 14 experiments covering print statements, data types, operators, input/output, conditional statements, loops, functions, decorators, iterators and generators. The experiments involve writing Python code to perform tasks like addition, comparison, type identification, looping, nested conditional logic and applying decorators.

Uploaded by

Taran Kaur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

EXPERIMENT TITLE LAB

NO. MAPPING
Study of Basic Data Types, Loops, Control Flow and
1 Decorators LO 1
To understand the basic datatypes, I/O statement use in python and to
AIM: study the control flow and looping statements and to implement the
Decorators, Iterators and Generators.

Name: TARAN KAUR VALECHA


Roll No: 60
Div: D2B
Date of Performance: 26/08/2023

Program 1.1:
Basic data types, Operators, expressions and Input Output Statements

Experiment 1.1 : PRINT STATEMENTS

INPUT
print("taran kaur valecha","D2B")
site_name='vivekanand education society instituion of technology'
print(site_name)
site_name='VESIT CHEMBUR'
print(site_name)
A,B,C = 5,4.2,'Hello'
print(A)
print(B)
print(C)
site1=site2='VESIT'
print (site1)
print (site2)

OUTPUT
EXPERIMENT 1.1.2 : IDENTIFY TYPES

INPUT:

print("taran kaur valecha","D2B")


num1 = 14
print(num1, 'is of type',type(num1))
num2 = 3.14
print(num2, 'is of type',type(num2))
num3 = 8+4j
print(num3, 'is of type',type(num3))

OUTPUT:

EXPERIMENT 1.1.3 : PRINT DATA OF TYPES

INPUT

print("taran kaur valecha","D2B")


num1 = int(2.3)
print(num1)
num2 = int(-3.14)
print(num2)
num3 = float(8)
print(num3)
num4 = complex(8+4j)
print(num4)

OUTPUT

EXPERIMENT 1.1.4 : ADDITION OF TWO NUMBERS (ONLY ASSIGNING)

INPUT
print("taran kaur valecha","D2B")
num1= 11
num2= 12
sum= float(num1)+float(num2)
print('addition of {0} and {1} is {2}'.format(num1,num2,sum))

OUTPUT

EXPERIMENT 1.1.5 : ADDITION OF TWO NUMBERS( DATA FROM THE


USER)

INPUT
print("taran kaur valecha","D2B")
num1=float(input('enter the first number:'))
num2=float(input('enter the second number:'))
sum=num1+num2
print(f"addition of {num1} and {num2} is {sum}")
OUTPUT

EXPERIMENT 1.1.6

INPUT

print("Taran kaur valecha_D2B_60")


number1 = float(input('Enter first number: '))
number2 = float(input('Enter second number: '))
sum = number1 + number2
sub = number1 - number2
divi = number1/number2
mult = number1 * number2
remainder = number1%number2
power = number1**number2
print('Addition of {0} and {1} is {2}'.format(number1,number2,sum))
print('Subtraction of {0} and {1} is {2}'.format(number1,number2,sub))
print('Division of {0} and {1} is {2}'.format(number1,number2,divi))
print('Multiplication of {0} and {1} is {2}'.format(number1,number2,mult))
print('Remainder of {0} and {1} is {2}'.format(number1,number2,remainder))
print('power of {0} and {1} is {2}'.format(number1,number2,power))

OUTPUT
EXPERIMENT 1.1.7 A :ASSIGNMENT OPERATORS

INPUT

print("Taran kaur valecha_D2B_60")

number1 = 9
number2 = 7
number1 += number2
print('Addition of two numbers is ',number1)
number1 -= number2
print('Subtraction of two numbers is ',number1)
number1 *= number2
print('Multiplication of two numbers is ',number1)
number1 /= number2
print('Division of two numbers is ',number1)
number1 %= number2
print('Remainder of two numbers is ',number1)
OUTPUT

EXPERIMENT 1.1.7 B: ASSIGNMENT OPERATORS

INPUT

print("Taran kaur valecha_D2B_60")

number = int(input('Enter an integer: '))


print('Table of',number,'is:')
print(number ,'x 1 =', number*1)
print(number ,'x 2 =', number*2)
print(number ,'x 3 =', number*3)
print(number ,'x 4 =', number*4)
print(number ,'x 5 =', number*5)
print(number ,'x 6 =', number*6)
print(number ,'x 7 =', number*7)
print(number ,'x 8 =', number*8)
print(number ,'x 9 =', number*9)
print(number ,'x 10 =', number*10)

OUTPUT
1.1.8 : COMPARISON OPERATOR

INPUT
print("Taran kaur valecha_D2B_60")

num1=12
num2=13
#to check number1 = number2
print("num1 == num2", num1 == num2)
#prints false
#to check or to compare num1=num2
print("num1 != num2", num1 != num2)
#prints true
#to compare num1!=num2
print("num1>num2", num1 > num2)
#prints false
#to compare num1>num2
print("num1<num2", num1<num2)
#prints true
#to compare num1<num2
print("num>=num2", num1>=num2)
#prints false
#to compare num1>=num2
print("num1<=num2", num1<=num2)
#prints false
#to compare num1<=num2

OUTPUT

1.1.9 IDENTITY OPERATOR

INPUT
print("Taran kaur valecha_D2B_60")

a1=15
b1=15
a2='TARANKAUR'
b2='TARANKAUR'
a3=[1,2,3]
b3=[1,2,3]
print('a1 is b1', a1 is b1)
#prints true
print('a2 is not b2', a2 is not b2)
# prints false
print('a3 is b3', a3 is b3)
#prints true

OUTPUT
1.1.10 MEMBERSHIP OPERATOR

INPUT

print("Taran kaur valecha_D2B_60")

FULLNAME="Taran Kaur Valecha"


dictionary1={1:'a', 2:'Taran'}
print('T'in FULLNAME)
#PRINTS TRUE
print('Kaur' not in FULLNAME)
#PRINTS FALSE
print('T'in dictionary1)
#PRINTS FALSE
print('T'in dictionary1)
#PRINTS FALSE

OUTPUT

<<< Copy Source Code and Paste Output >>>


Program 1.2:
Control flow statements: Conditional statements (if, if…else, nested if)

INPUT

print("Taran kaur valecha_D2B_60")

number=input('enter number:')
if int(number)>0:
print('number is positive')
else:
print('number is negative')

OUTPUT

1.2.2 NESTED IF ELSE


# To check the largest number out of three numbers

INPUT

print("Taran kaur valecha_D2B_60")

num1=int(input('enter an integer:'))
num2=int(input('enter an integer:'))
num3=int(input('enter an integer:'))
#outer if statement
if(num1>num2):
#inner if statement
if(num1>num3):
print('num1 is the largest', num1)
else:
print('num3 is the largest', num3)
#outer if done
else:
#inner if statement
if(num2>num3):
print("num2 is the largest", num2)

else:
print('num3 is the largest', num3)

OUTPUT

1.2.3 ELIF STATEMENTS

INPUT

print("Taran kaur valecha_D2B_60")

marks=int(input('enter your marks:'))


if marks > 85 and marks<=100:
print("congratulations you have scored A grade")
elif marks>60 and marks>85:
print("you have scored B+ grade")
elif marks>40 and marks<=60:
print("you have scored B grade")
elif marks>30 and marks<=40:
print("you have scored C grade")
else:
print("sorry you have failed")

OUTPUT
<<< Copy Source Code and Paste Output >>>

Program 1.3:
Looping in Python (while loop, for loop, nested loops)

INPUT

print("Taran kaur valecha_D2B_60")


#to print first 10 numbers
for value in range(1,11):
print(value)
value+=value

OUTPUT

EXAMPLE 2

INPUT

print("Taran kaur valecha_D2B_60")


#to print first 25 even numbers
for even in range(1,51):
if even%2==0:
print(even,end=" ")

OUTPUT

Taran kaur valecha_D2B_60


>
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 >

PROGRAM 1.3.2: FOR LOOP WITH LIST

INPUT
print("Taran kaur valecha_D2B_60")
languages=['swift','python','go','javascript']
#access then of a list using for loop
for language in languages:
print(languages)
digit=[7,4,9,15,1]
for i in digit:
print("digit in list is: ")
else:
print('list is empty')

OUTPUT
PROGRAM 1.3.3

INPUT

print("Taran kaur valecha_D2B_60")


lst=[ ]
size=int(input("please enter the size: "))
for i in range(0,size):
print("please enter the number:", i+1)
x=int(input())
lst.append(x)
print(lst)

OUTPUT
PROGRAM 1.3.4: PRINT RANGE USING WHILE LOOP

INPUT
print("Taran kaur valecha_D2B_60")
start=int(input('enter the start number:'))
end=int(input('enter the end number:'))
while start<=end:
if start%2==0:
print(start,end=' ')
start+=1

OUTPUT
EXPERIMENT 1.3.5: SQUARING

INPUT
print("Taran kaur valecha_D2B_60")

lst=[2,3,6,4,8]
size=int(input("please enter the size: "))
square = []
while lst :
square.append((lst.pop())**2)
print(square)

OUTPUT

EXPERIMENT 1.3.6: REVERSING NUMBER

INPUT
print("Taran kaur valecha_D2B_60")
lst=[ ]
size=int(input("please enter the size: "))
for i in range(0,size):
print("please enter the number:", i+1)
x=int(input())
lst.append(x)
number=int(input('enter a number:'))
print('number:', number)
reverse_number=0
while number!=0:
digit=number%10
reverse_number=reverse_number*10+digit
number//=10
print('reverse_number is:', str(reverse_number))

OUTPUT

PROGRAM 1.3.7 MULTIPLE LOOPS SORTED NUMBERS

INPUT

print("Taran kaur valecha_D2B_60")


lst=[ ]
size=int(input("please enter the size: "))
for i in range(0,size):
print("please enter the number:", i+1)
x=int(input())
lst.append(x)
for i in range(0,size):
for j in range(0,size-1):
if lst[j]>lst[j+1]:
temp=lst[j+1]
lst[j+1]=lst[j]
print("sorted list", lst)

OUTPUT

ASSIGNMENT

INPUT
print("Taran kaur valecha_D2B_60")

print("Taran kaur valecha_D2B_60")


n = int(input("Enter no of students: "))
list_1 = []
for i in range(n):
student = input("enter your name:")
physics = int(input("Enter your physics marks: "))
chemistry = int(input("Enter your chemistry marks: "))
maths = int(input("Enter your maths marks: "))
sum = physics + chemistry + maths
percentage = (sum / 300) * 100
list_1.append([student, percentage])
for i in range(n):
for j in range(n-1):
if list_1[j][1] < list_1[j + 1][1]:
temp = list_1[j]
list_1[j] = list_1[j]
list_1[j] = temp
print("arranged list for students:", list_1)

OUTPUT
Program 1.4: Decorators, Iterators and Generators

EXPERIMENT 1.4.1

INPUT

print("Taran kaur Valecha_D2B_60")


def div(a,b):
return a/b
a=int(input("enter the value of a:"))
b=int(input("enter the value of b:"))
c=div(a,b)
print(c)

OUTPUT

EXPERIMENT 1.4.2 : DECORATOR FUNCTION

INPUT

print("Taran kaur Valecha_D2B_60")


def check(func):
def inside(a,b):
if b==0:
print("can't divide by 0")
return
return func(a,b)
return inside
@check
def div(a,b):
return a/b
a=int(input("enter your value for a: "))
b=int(input("enter your value for b: "))
print (div(a,b))

OUTPUT

EXPERIMENT 1.4.3 : ITERATOR IN PYTHON

INPUT

#a Python iterator object must implement two special methods, iter_() and
a = [4, 7, 0, 15, 40, 91]
for element in a:
print (element)
print("_____")
iterator=iter (a)
for x in iterator:
print (x)
iterator=iter (a)
print("____")
print (next (iterator))
print (next (iterator))
print (next (iterator))
print (next (iterator))
print (next (iterator))
print (next (iterator))

OUTPUT
EXPERIMENT 1.4.4: GENERATOR IN PYTHON

INPUT

print("Taran kaur valecha_D2B_60")

def fib (size):


a,b=0,1
while True:
c=a+b
if c< size:
yield c
a=b
b=c
else:
break
x=int (input("enter size: "))
gen=fib (x)

print (next (gen))


print (next (gen))
print (next (gen))
print (next (gen))
print (next (gen))
print (next (gen))

print (next (gen))

OUTPUT

<<< Copy Source Code and Paste Output >>>


EXPERIMENT TITLE LAB
NO. MAPPING
Implementation of List, Tuples, String Functions, User
2 Defined Functions and Arrays. LO 1 & LO 2
To understand the implementation of various Built-in functions of List
AIM: and Tuples, Set and Strings, Implementation of Arrays using Numpy
Libararies and use of lambda functions

Name: TARAN KAUR VALECHA


Roll No: 60
Div: D2B
Date of Performance: : 09/09/2023

Program 2.1:
Different List and Tuple operations using Built-in functions

<<< Copy Source Code and Paste Output >>>

Experiment 2.1.1

INPUT
print('Taran kaur valecha_D2B_60')
lst=[]
size=int(input("Enter the Size "))
for i in range(0,size):
print("Enter Number:",i+1)
x=int (input())
lst.append(x)
print(lst)
#accessing list
print(lst[1])
print(lst[5])
# slice the list, for that create a list of atleast 6 numbers above
print(lst[1:4])

OUTPUT
Experiment 2.1.1

Input
print('Taran kaur valecha_D2B_60')

OLD=["HELLO ","VESIT "]


lst=[]
size=int(input("Enter the Size "))
for i in range(0,size):
print("Enter Number:" ,i+1)
x=int (input())
lst.append(x)
#CONCATE OF TWO LIST
OLD.extend(lst)
print("OLD EXTENDED",OLD)
NEW=OLD #make a list copy
print ("COPIED TO NEW ",OLD)
OLD[1]="CHANGE" #CHANGE CONTENT
print ("CHANGES IN NEW ",NEW)
del NEW[0]
print ("DELETE IN NEW ",OLD)
print ("TOTAL LENGTH IF A LIST IS ",len(NEW))

Output
Experiment 2.1.3

Input

print('Taran kaur valecha_D2B_60')

#Different type of tuples


#Empty tuple
my_tuple = ()
print (my_tuple)
#Tuple having integers
my_tuple = (1,2,3)
print(my_tuple)
#tuple with mixed datatype
my_tuple = (1,"Hello",3.4)
print(my_tuple)
#nested tuple
my_tuple = ("mouse",[8,4,6],(1,2,3))
print (my_tuple)

Output

Exp 2.1.4

Input

print('Taran kaur valecha_D2B_60')

languages=('Python','Swift','C++')
#iterating through the tuple
for language in languages:
print(language)
print('C' in languages) #FALSE
print('Python' in languages) #TRUE

Output

Program 2.2:
Built-in Set and String functions

<<< Copy Source Code and Paste Output >>>

Exp 2.2.1
Input
print("Taran kaur valecha_D2B_60")
# create string type variables
name="Python"
print (name)
message ="I love Python."
print (message)
# multiline string
message ="""
Never gonna give you up
Never gonna let you down
"""
print (message)
#Python Strings are immutable
message [0] = 'M' # CANNOT BE CHANGED
print (message)

Output

Exp 2.2.2
Input
print("Taran kaur valecha_D2B_60")
str1 = "Hello, world!"
str2= " I love Python."
str3= "Hello, world!"
# compare str1 and str2
print (str1 == str2)
#compare str1 and str3
print (str1 == str3)
# string concat
str1=input ("Enter 1st string ")
str3=str1+str2
str2=input("Enter 2nd string ")
print (str3)
for letter in str3:
print (letter)
#Python String Formatting (f-Strings)
name= 'VESIT'
country = 'INDIA'
print (f' {name} is from {country}')

Output
Exp 2.2.3
Input
print("Taran kaur valecha_D2B_60")
numbers= {100, 21, 34, 54, 12, 6}
print('Initial Set:', numbers)
# using add() method
numbers.add(32)
numbers.add(101)
print ('Updated Set:', numbers)
#copy function
langs ={'Python', 'C++', 'Java'}
copiedLangs= langs.copy()
print("Original Set: ", langs)
print ("Copied Set: ", copiedLangs)

Output

Exp 2.2.4
Input
print("Taran kaur valecha_D2B_60")

# First set
A = {1, 3, 5}
# Second set
B = {0, 2, 4}
# Perform union operation using |
print('Union using |:', A | B)
# Perform union operation using union()
print('Union using union():', A.union(B))
# DIFFERENCE
nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 8}
nums3 = {3, 5, 8, 9, 10}
diff = nums1 - nums2 - nums3
print('Numbers Differences:', diff)
cities = {'Bangalore', 'Mumbai', 'New York', 'Hong Kong', 'Chicago'}
indianCities = {'Bangalore', 'Mumbai'}
nonindiancities = cities - indianCities
print("Non-Indian Cities:", nonindiancities)

Output

Program 2.3:
Basic Array operations on 1-D and Multidimensional arrays using Numpy

Program 2.3

Exp 2.3.1
Input
print("Taran Kaur valecha_D2B_60")

import numpy as np
# create numpy array
a = np.array([5, 8, 12])
print(a)

import numpy as np
A = np.array([[1,2,3], [3,4,5]])
print(A)
A = np.array([[1.1,2,3],[3,4,5]]) # array of floats
print(A)
A = np.array([[1,2,3], [3,4,5]], dtype = complex) # array of complex numbers
print(A)

Output
Exp 2.3.2

Input
print("Taran Kaur valecha_D2B_60")

import numpy as np

A = np.array([[1,4,5,12], [-5,8,9,0], [-6,7,11,19]])


# first element of first row
print("A[0][0] =",A[0][0])
#third elemet of secomd row
print ("A[1][2] =", A[1][2])
# last element of row
print("A[-1][-1] =", A[-1][-1])

#accessing rows
A = np.array([[1,4,5,12], [-5,8,9,0], [-6,7,11,19]])
print("A[0] =", A[0]) # first row
print("A[2] =", A[2]) # third row
print("A[-1] =", A[-1]) # last row( 3rd row in this case)

Output
Exp 2.3.3

Input
print("Taran Kaur valecha_D2B_60")

import numpy as np
A = np.array([[2,4], [5,-6]])
B = np.array([[9,-3],[3,6]])
print("MATRIX A")
print(A)
print("MATRIX B")
print(B)
C = A+B
print("additon of A and b ")
print(C)
#multiplication
C = A.dot(B)
print("multiplication of A and B ")
print(C)

Output
<<< Copy Source Code and Paste Output >>>

Program 2.4:
Implementing User defined and Anonymous Functions

Exp 2.4.1
Input
print("Taran Kaur Valecha_D2B_60")

def print_factors(x):
print("the factors of",x,"are:")
for i in range(1, x+1):
if x%i == 0:
print(i)

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


print_factors(num)

Output

Exp 2.4.2
Input
print("Taran Kaur Valecha_D2B_60")

# task 1 = please change the below code into user define mode
# task 2 = print all armrstrong number till user input given range

#python program to check if the number is an armstrong number or not


#to take input from the user
num= int(input("Enter a number:"))
#initialize sum
sum = 0
# to find the sum of the cube of each digit
temp = num
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

Exp 2.4.3
Input
print("Taran Kaur valecha_D2B_60")

square = lambda a: a*a


# call lambda function
a=int(input("enter number: "))
result = square(a)
print(result)

mul = lambda a,b: a*b


# call lambda function
result = mul(5,3)
print(result)

Output
Exp 2.4.4

Input
print("Taran Kaur Valecha_D2B_60")

alist =[lambda arg=x: arg*10 for x in range(1,5)]

#iterate on each lambda


# abd invoke the function to get the calculated value
for item in alist:
print(item())

ages = [13,90,17,59,21,60,5]
adults = list(filter(lambda age: age>18, ages))
print(adults)

Output

ASSIGNMENT

INPUT

print("Taran kaur valecha_D2B_60")


#python program to check if the number is an armstrong number or not
#take input from the user
num=int(input ("Enter number: "))
#initialize sum
sum=0
#find the sum of the cube of each digit
temp=num
while temp>0:
digit=temp&10
sum+=digit**4
temp//=10
#display the result
if num==sum:
print(num,"is an armstrong number")
else:
print(num,"is not an armstrong number")

<<< Copy Source Code and Paste Output >>>


EXPERIMENT TITLE LAB
NO. MAPPING
Python Programs to implements Basic Object Oriented
3 Concepts LO 1 & LO 3
AIM: Implementation the Concept of Object Oriented Programming using
Python Language

Name: TARAN KAUR VALECHA


Roll No: 60
Div: D2B
Date of Performance: 16/09/2023

Program 3.1:
WAP to implement Classes, Objects, Constructors, Inner class and Static method

Experiment 3.1.1

Input

print("Tarankaurvalecha_D2B_60")
# define a class
class bike:
name = ""
gear = 0
# create a object of class
bike1 = bike()
# access attributes and assign values
bike1.gear = 11
bike1.name = "mountain bike"

print ("gear: ", bike1.gear)


print("name:", bike1.name)

Output
Experiment 3.1.2
Input
print("Tarankaurvalecha_D2B_60")
# define a class
class bike:
name = ""
gear = 0
def display(self):
print("gear:", self.gear)
print("name:", self.name)
# create a object of class
bike1 = bike()
# access attributes and assign values
bike1.gear = 11
bike1.name = "hero"

print ("gear: ", bike1.gear)


print("name:", bike1.name)

#creating another object of same class


bike2 = bike()
bike2.gear = 12
bike2.name = "bajaj"
bike2.display()

print ("gear: ", bike2.gear)


print("name:", bike2.name)

Output
Experiment 3.1.3
Input
print("Tarankaurvalecha_D2B_60")
# create a class
class room:
length = 0.0
breadth = 0.0

# method to calculate area

def calculate_area(self):
print ("area of room= ", self.length* self.breadth)

#create object of room class


study_room = room()

#assign value to all the attributes


study_room.length = 42.5
study_room.breadth = 30.8

#access method inside class

study_room.calculate_area()

Output

Experiment 3.1.4
Input
print("Taran kaur valecha_D2B_60")
class vesit:
#default constructor
def __init__(self):
self.division="d2b"
#a method for printing data members
def print(self):
print(self.division)
#creating object of the class
student1=vesit()
student2=vesit()
#calling the instance method using the object obj
student1.print()
student2.print()

Output

Experiment 3.1.5
Input
print("Taran kaur valecha_D2B_60")
class Sum:
num1= 0
num2= 0
total= 0
#parameterized constructor
def __init__(self, f, s):
self.num1=f
self.num2=s
def display(self):
print('First number='+ str(self.num1))
print('Second number='+ str(self.num2))
print('Addition of two numbers='+ str(self.total))
def add(self):
self.total= self.num1 + self.num2
#creating object of the class
#this will invoke parameterized constructor
obj1=Sum(1000,2000)
#creating object of same class
obj2=Sum(10,20)
#perform addition on obj1
obj1.add()
#perform addition on obj2
obj2.add()
#display result of obj1
obj1.display()
#display result of obj2
obj2.display

Output

Exp 3.1.6
Input
print("Taran kaur valecha_D2B_60")

class Color:
# Constructor method
def __init__(self):
# Object attributes
self.name = 'Green'
self.lg = self.Lightgreen()
def show(self):
print('Name:', self.name)
class Lightgreen:
def __init__(self):
self.name = 'Light Green'
self.code = '024avc'
def display(self):
print('Name:', self.name)
print('Code:', self.code)
# Create Color class object
outer = Color()
# Method calling
outer.show()
# Create a Lightgreen inner class object
g = outer.lg
# Inner class method calling
g.display()

Output

Exp 3.1.7

Input
print("Taran kaur valecha_D2B_60")

class Myclass:
def __init__(self, value):
self.value = value
@staticmethod
def get_max_value(x, y):
return max(x, y)
# Create an instance of Myclass
obj = Myclass(10)
print(Myclass.get_max_value(20, 30))
print(obj.get_max_value(20, 30))

Output
Program 3.2:
WAP to implement Different types of Inheritance
Exp 3.2.1
Input
print("Taran kaur valecha_D2B_60")

class parent:
def getno(self):
self.a = int(input('Enter first no: '))
self.b = int(input('Enter second no: '))
def display(self):
print('First number:', self.a)
print('Second number:', self.b)
class child(parent):
def add(self):
self.c = self.a + self.b
print('Total:', self.c)
new = child()
new.getno()
new.display()
new.add()

Output

Exp 3.2.2
Input
print("Taran kaur valecha_D2B_60")
class org:
def getorg(self):
self.y = input('Enter organisation name: ')
class inst(org):
def getinst(self):
self.x = input('Enter institute name: ')
class branch(inst):
def getbranch(self):
self.branchname = input('Enter branch name: ')
def show(self):
print('Organisation:', self.y)
print('Institute:', self.x)
print('Branch:', self.branchname)
new = branch()
new.getorg()
new.getinst()
new.getbranch()
new.show()

Output

EXP 3.2.3
INPUT
print("Taran kaur valecha_D2B_60")

class timeone:
def gettime1(self):
self.min = int(input('Enter minutes: '))
class timetwo:
def gettime2(self):
self.sec = int(input('Enter seconds: '))
class addtime(timeone, timetwo):
def add(self):
self.add=self.min*60+self.sec
x=self.add/3600
print('total time',x)
new = addtime()
new.gettime1()
new.gettime2()
new.add()

OUTPUT

EXP 3.2.4
INPUT
print("Taran kaur valecha_D2B_60")

# Python program to demonstrate


# hierarchical inheritance
# Base class
class Parent:
def func1(self):
print('This function is in the parent class')
# Derived class 1
class Child1(Parent):
def func2(self):
print('This function is in child1')
# Derived class 2
class Child2(Parent):
def func3(self):
print('This function is in child2')
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()

OUTPUT

Program 3.3:
Polymorphism using Operator overloading, Method overloading, Method
overriding,
Abstract class, Abstract method and Interfaces in Python.

EXP 3.3
EXP3.3.1
INPUT
print("Taran kaur valecha_D2B_60")

class Complex:
def __init__(self, a, b):
self.a = a
self.b = b
def __add__(self, other):
return self.a + other.a, self.b + other.b
ob1 = Complex(1, 7)
ob2 = Complex(2, 5)
ob3 = ob1 + ob2
print(ob3)

OUTPUT
EXP 3.3.2
INPUT
print("Taran kaur valecha_D2B_60")

class Calculate:
def add(self, *args):
result = 0
for param in args:
result += param
#print ("Result: {}".format (result))
print(result)
c1 = Calculate()
c1.add(10, 20, 30)
c1.add(10, 20)

OUTPUT

EXP 3.3.3
INPUT
print("Taran kaur valecha_D2B_60")

class Parent():
# Parent's show method
def display (self):
print ("Inside Parent")
# Inherited or Sub class (Note Parent in bracket)
class Child (Parent):
#Child's show method
def show (self):
print("Inside Child")
# Inherited or Sub class (Note Child in bracket)
class GrandChild(Child):
# Child's show method
def show (self):
print ("Inside GrandChild")
# Driver code
g= GrandChild()
g.show()
g.display()

OUTPUT

EXP 3.3.4
INPUT
print("Taran kaur valecha_D2B_60")

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")
# overriding abstract method
# Driver code
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()

OUTPUT

ASSIGNMENT
PASSWORD GENERATOR
INPUT

print("Taran kaur valecha_D2B_60")


print("welcome to Password generator program!")
import random
import string
def generate_password(num_letters, num_symbols, num_numbers):
# Define character sets for different types of characters
lowercase_letters = string.ascii_lowercase
uppercase_letters = string.ascii_uppercase
digits = string.digits
symbols = '!@#$%^&*()_-+=<>?/[]{}|'
# Initialize an empty list to store the password characters
password_chars = []
# Generate random letters
for _ in range(num_letters):
password_chars.append(random.choice(lowercase_letters + uppercase_letters))
# Generate random symbols
for _ in range(num_symbols):
password_chars.append(random.choice(symbols))
# Generate random numbers
for _ in range(num_numbers):
password_chars.append(random.choice(digits))
# Shuffle the password characters to make it random
random.shuffle(password_chars)
# Combine the characters to create the password
password = ''.join(password_chars)
return password
if __name__ == "__main__":
# Prompt the user for the number of letters, symbols, and numbers
num_letters = int(input("Enter the number of letters in the password: "))
num_symbols = int(input("Enter the number of symbols in the password: "))
num_numbers = int(input("Enter the number of numbers in the password: "))
# Generate and print the password
password = generate_password(num_letters, num_symbols, num_numbers)
print("Generated Password:", password)

OUTPUT
EXPERIMENT TITLE LAB
NO. MAPPING
Exploring the concept of Modules, Packages and
4 Multithreading LO 1 & LO 4
AIM: To understand creating packages and importing them, to comprehend the
threading concept and implement the synchronization of multithreading
and deadlocks

Name: TARAN KAUR VALECHA


Roll No: 60
Div: D2B
Date of Performance: 14/10/2023

Program 4.1:
Creating User-defined modules/packages and import them in a program

EXP 4.1.1

PACKAGE FILE
def sub(a, b):
result = a - b
return result

def add(a, b):


result = a + b
return result

def mul(a, b):


result = a * b
return result

def div(a, b):


result = a / b
return result

INPUT
OUTPUT

EXP 4.1.2
PACKAGE FILE

class Student:

def __init__(self, student):


self.name = student['name']
self.gender = student['gender']
self.year = student['year']

def get_student_details(self):
return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}"
class Faculty:

def __init__(self, faculty):


self.name = faculty['name']
self.subject = faculty['subject']

def get_faculty_details(self):
return f"Name: {self.name}\nSubject: {self.subject}"

INPUT

OUTPUT
Program 4.2:
Creating user defined multithreaded application with thread synchronization and
deadlocks

EXP 4.2.1

INPUT

print("Taran kaur valecha_D2B_60")

from threading import *


from time import sleep
class hello(Thread):
def run(self):
for i in range(5):
sleep(1)
print("hello")
class hi(Thread):
def run(self):
for i in range(5):
sleep(0.5)
print("hi")
t1=hello()
t2=hi()
t1.start()
sleep(0.2)
t2.start()

t1.join()

t2.join()
print("bye")
OUTPUT

EXP 4.2.2
INPUT

print("Taran kaur valecha_D2B_60")

# python program to illustrate the concept


# of threading
# importing the threading module
from os import name
import threading
def print_cube(num):
# function to print cube of given number
print("cube: {}".format(num * num * num))

def print_square(num):
# function to print square of the given number
print("square: {}".format(num * num))

if name == '__name__':
# creating thread

t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))

# starting thread 1
t1.start()
# starting thread 2
t2.start()

# wait until thread 1 is completely executed


t1.join()
# wait until thread 2 is executed completely
t2.join()

# both threads completely executed


print("done")

OUTPUT
Program 4.3
Creating a menu driven application which should cover all the built-in exceptions
in
python

INPUT

print("Taran Kaur Valecha_D2B_60")


# menu driven program to calculate perimeter and area of different shapes
# declaring all the required functions with the the calculations of perimeter of
different shapes
def per_circle(radius):
perimeter = 2 *3.14*radius
print("perimeter of circle:", perimeter)
def per_triangle(side1, side2, side3):
perimeter= side1+side2+side3
print("perimeter of triangle:", perimeter)
def per_rectangle(height, width):
perimeter = 2*(height + width)
print("Perimeter of rectangle: ",perimeter)
def per_square(side):
perimeter= 4*side
print("perimeter of square:", perimeter)
# declaring all the required functions with the calculations of area of different
shapes
def a_circle(radius):
area=3.14*radius*radius
print("Area of circle: ", area)

def a_triangle(base,height):
area= base*height/2
print("area of triangle:", area)
def a_rectangle(base,width):
area= base*width
print("area of rectangle:", area)
def a_square(side):
area = side * side
print("area of square:", area)
#heading of menu-driven approach
print("\nWELCOME TO MENU DRIVEN PROGRAM! TRY CALCULATING
PERIMETER AND AREA OF DIFFERENT GEOMETRIC SHAPES ")
#using the while loop to print menu list
while True:
print("\nMENU")
print("1.Circle")
print("2.Triangle")
print("3.Rectangle")
print("4.Square")
print("5.Exit")
shape_choice = int(input("\nEnter your choice of shape for calculations: "))
if shape_choice == 1:
while True:
print("\n1.calculate perimeter of circle")
print("2. calculate area of circle")
print("3. Exit")
choice1=int(input("\nEnter choice for calculations: "))
#Calling the relevant method based on users choice using if-else loop
if choice1 == 1:
radius = int (input ("Enter Radius of Circle: "))
per_circle (radius)
elif choice1 == 2:
radius = int(input ("Enter Radius of Circle: "))
a_circle (radius)
elif choice1 == 3:
break
else:
print ("Incorrect Choice!")
elif shape_choice==2:
while True:
print("\n1.Calculate perimeter of Triangle")
print("2.calculate area of Triangle")
print("3.Exit")
choice1 = int(input("\nEnter choice of calculations: "))
if choice1 == 1:
side1 = int(input("enter length of side1: "))
side2 = int(input("enter length of side2: "))
side3 = int(input("enter length of side3: "))
per_triangle(side1,side2,side3)
elif choice1 == 2:
base = int(input('enter base of triangle: '))
height = int(input("enter height of triangle: "))
a_triangle(base,height)
elif choice1 ==3:
break
else:
print("incorrect choice!")
elif shape_choice == 3:
while True:
print("\n1.Calculate perimeter of rectangle")
print("2.Calculate area of rectangle")
print("3.Exit")
choice1 = int(input("\nEnter choice of calculations: "))
if choice1 == 1:
height = int(input("enter height of rectangle: "))
width = int(input("enter width of rectangle: "))
per_rectangle(height,width)
elif choice1 == 2:
height = int(input("enter height of rectangle: "))
width = int(input("enter width of rectangle: "))
a_rectangle(height,width)
elif choice1 == 3:
break
else:
print("Incorrect choice!")
elif shape_choice ==4:
while True:
print("\n1.calculate perimeter of square")
print("2. calculate area of square")
print("3. exit")
choice1 = int(input("\nEnter choice of calculations: "))
if choice1==1:
side = int(input("\nEnter side of square: "))
per_square(side)
elif choice1 == 2:
side = int(input("enter side of square: "))
a_square(side)
elif choice1 == 3:
break
else:
print("Incorrect choice!")
# exit condition to get out of the while loop
elif shape_choice == 5:
print("Thank you! see you again.")
break
else:
print("Incorrect choice.Please, try again.")

OUTPUT
EXPERIMENT TITLE LAB
NO. MAPPING
Programs to Implement File Handling
5 LO 1 & LO 5
AIM: To understand the implementation of File Handling Operation using
Python

Name: TARAN KAUR VALECHA


Roll No: 60
Div: D2B
Date of Performance: 21/10/2023

Program 5.1: Different File Handling operations in Python

Exp 5.1.1 - write and read the file

Input
print('Taran kaur valecha_D2B_60')
file=open("Tarankaur_D2B_60.txt",'w')
file.write('This will write a command from VESIT\n')
file.write('it allows us to write in a particular file')
file.close()
file=(open("Tarankaur_D2B_60.txt","r"))
print(file.read())

Output

EXP 5.1.2 -APPEND AND READ FILE

INPUT
print('Taran kaur valecha_D2B_60')
file=open("Tarankaur_D2B_60.txt",'w')
file=open("filename","w")
file.write('This will add line to existing file')
file.close()
file=open("filename","r")
print(file.read())

Output

EXP 5.1.3
INPUT

def create_file(filename):
try:
with open(filename,'w')as F:
F.write('Hello, VESITIAN!\n')
print("File"+filename+"created succesfully.")
except IOError:
print("Error: could not create File"+filename)
def read_file(filename):
try:
with open(filename,'r')as F:
contents=F.read()
print(contents)
except IOError:
print("Error: could not read file."+filename)
def append_file(filename,text):
try:
with open(filename,'a')as F:
F.write(text)
print("Text appended to file"+filename)
except IOError:
print("Error: could not append to file."+filename)
def rename_file(filename,new_filename):
try:
os.rename(filename,new_filename)
print("File"+filename+"renamed to"+new_filename+"successfully")
except IOError:
print("Error: could not rename file."+filename)
def delete_file(filename):
try:
os.remove(filename)
print("File"+filename+"deleted succesfully")
except IOError:
print("Error: could not delete file."+filename)
if __name__=='__main__':
filename="example.txt"
new_filename="new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename,"This is some additional text.\n")
read_file(filename)
rename_file(filename,new_filename)
read_file(new_filename)
delete_file(new_filename)

OUTPUT

EXP 5.2.1
INPUT

from tkinter import *


root = Tk()
frame= Frame (root)
frame.pack()
bottomframe = Frame (root)
bottomframe.pack ( side = BOTTOM )
Badd= Button (frame, text="Add", fg="red")
Badd.pack()
Bsub= Button (frame, text="Subtract", fg="green")
Bsub.pack (side = RIGHT)
Bmul = Button (frame, text="Multiply", fg="blue")
Bmul.pack (side = LEFT)
Bdiv = Button (bottomframe, text="Divide", fg="black")
Bdiv.pack(side = BOTTOM)
root.mainloop()

OUTPUT

EXP 5.2.2
Input

from tkinter import *


root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack(side = BOTTOM)
b1 = Button(frame,text='Red',fg ='red')
b1.pack(side=LEFT)
b2 = Button(frame,text='Pink',fg ='pink')
b2.pack(side=RIGHT)
b3 = Button(frame,text='Yellow',fg ='yellow')
b3.pack(side=TOP)
b4= Button(frame,text='Taran',fg ='black')
b4.pack(side=LEFT)
root.mainloop()

Output

EXP 5.2.3
Input

import tkinter as tk
def perform_operation():
try:
num1= float(entry_num1.get())
num2= float(entry_num2.get())
operator= operation_var.get()
if operator =="+":
result.set(num1+num2)
elif operator =="-":
result.set(num1 - num2)
elif operator=="*":
result.set(num1*num2)
elif operator=="/":
if num2 == 0:
result.set("Error: Division by zero")
else:
result.set(num1/num2)
except ValueError:
result.set("Error: Invalid input")
#Create the main window
root = tk.Tk()
root.title("Arithmetic Operations")
#Create entry fields for numbers
entry_num1=tk.Entry(root, width=10)
entry_num2=tk.Entry(root, width=10)
#Create a label for the result
result = tk.StringVar()
result_label = tk.Label(root, textvariable=result)
#Create a dropdown for selecting the operation
operations=["+","-","*","/"]
operation_var = tk.StringVar()
operation_var.set("+") # Default operation is addition
operation_menu = tk.OptionMenu(root, operation_var, *operations)
#Create a button to perform the operation
calculate_button= tk.Button(root, text="Calculate", command=perform_operation)
#Grid layout for widgets
entry_num1.grid(row=0, column=0)
operation_menu.grid(row=0, column=1)
entry_num2.grid(row=0, column=2)
calculate_button.grid(row=1, column=0, columnspan=3)
result_label.grid(row=2, column=0, columnspan=3)
#Start the main event loop
root.mainloop()

OUTPUT
EXPERIMENT TITLE LAB
NO. MAPPING
6 Connecting GUI with databases to perform CRUD,
Importing Visualization. LO 1 & LO 5
AIM: Visualization using Matplotlib: Matplotlib with Numpy, working with
plots(line plot, bar graph, histogram, scatter plot, area plot, pie chart,etc),
working with multiple figures.

Name: TARAN KAUR VALECHA


Roll No: 60
Div: D2B
Date of Performance: 03/11/2023

Exp 6.1.1
Input

import tkinter as tk
import sqlite3

# Create the database and table if they don't exist


conn = sqlite3.connect("address_book.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS contacts (id INTEGER
PRIMARY KEY, name TEXT, email TEXT)")
conn.commit()

# Function to insert data into the database


def insert_data():
name = name_entry.get()
email = email_entry.get()
conn = sqlite3.connect("address_book.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO contacts (name, email) VALUES (?, ?)",
(name, email))
conn.commit()
conn.close()
update_listbox()
# Function to read data from the database and populate the listbox
def update_listbox():
listbox.delete(0, tk.END)
conn = sqlite3.connect("address_book.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM contacts")
rows = cursor.fetchall()
for row in rows:
listbox.insert(tk.END, f"Name: {row[1]}, Email: {row[2]}")
conn.close()

# Function to delete data from the database


def delete_data():
selected_item = listbox.get(listbox.curselection())
name = selected_item.split(",")[0].split(":")[1].strip()
conn = sqlite3.connect("address_book.db")
cursor = conn.cursor()
cursor.execute("DELETE FROM contacts WHERE name=?", (name,))
conn.commit()
conn.close()
update_listbox()

# Create the main application window


app = tk.Tk()
app.title("Address Book")
# Create and configure GUI components
name_label = tk.Label(app, text="Name:")
name_label.pack()
name_entry = tk.Entry(app)
name_entry.pack()
email_label = tk.Label(app, text="Email:")
email_label.pack()
email_entry = tk.Entry(app)
email_entry.pack()
create_button = tk.Button(app, text="Create", command=insert_data)
create_button.pack()
listbox = tk.Listbox(app, width=100)
listbox.pack()
update_listbox()
delete_button = tk.Button(app, text="Delete", command=delete_data)
delete_button.pack()
# Start the main loop
app.mainloop()

Output

Exp 6.1.2
Input

import numpy as np
import matplotlib.pyplot as plt
#generate sample data
x = np.linspace(0,10,100)
y = np.sin(x)
#line plot
plt.figure(1)
plt.plot(x,y,label = 'sin(x)')
plt.title('line plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()

#bar graph
categories =['A','B','C','D']
values = [5,10,8,12]

plt.figure(2)
plt.bar(categories, values)
plt.title('Bar Graph')
plt.xlabel('Categories')
plt.ylabel('Values')

#Histogram
data = np.random.normal(0, 1, 1000)
plt.figure(3)
plt.hist(data, bins=20)
plt.title('Histogram')
plt.xlabel('Value')
plt.ylabel('Frequency')

# Scatter plot
x = np.random.rand(50)
y = np.random.rand(50)

plt.figure(4)
plt.scatter(x, y)
plt.title('Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# area plot
x = np.linspace(0, 5, 100)
y1=x
y2 = x**2
plt.figure(5)
plt.fill_between(x, y1, y2, alpha=0.5)
plt.title('Area Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Pie chart
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
plt.figure(6)
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('Pie Chart')
# Show all plots
plt.show()

OUTPUT
ASSIGNMENT 1
PACKAGE FILE:

class Library:
def __init__(self):
self.books = ["To Kill a Mockingbird","1984","Pride and Prejudice","The
Great Gatsby","The Catcher in the Rye",
"Brave New World","The Hobbit","Moby-Dick","War and
Peace","Crime and Punishment","The Lord of the Rings",
"The Chronicles of Narnia","The Grapes of Wrath","One Hundred
Years of Solitude","The Odyssey","The Illiad","Anna Karenina",
"The Brothers Karamazov","Frankenstein","Dracula","Wuthering
Heights","Jane Eyre","The Picture of Dorian Gray","Fahrenheit 451",
"The Road","The Hitchhiker's Guide to the Galaxy","A Song of Ice
and Fire","The Alchemist","The Little Prince","The Hunger Games",
"Harry Potter and the Philosopher's Stone","The Girl on the
Train","Gone Girl","The Da Vinci Code","The Help",
"The Fault in Our Stars","The Girl with the Dragon Tattoo","The Kite
Runner","The Maze Runner","Divergent","The Secret Garden",
"Charlotte's Web","The Wizard of Oz","Alice's Adventures in
Wonderland","The Name of the Wind","The Goldfinch","Educated",
"Where the Crawdads Sing","Becoming","Sapiens: A Brief History of
Humankind", "Homo Deus: A Brief History of Tomorrow"]

def add_book(self, book):


self.books.append(book)
print(f"{book} has been added to the library.")

def remove_book(self, book):


if book in self.books:
self.books.remove(book)
print(f"{book} has been removed from the library.")
else:
print(f"{book} is not in the library.")
def display_books(self):
if self.books:
print("Books in the library:")
for book in self.books:
print(book)
else:
print("The library is empty.")

def search_book(self, title):


found_books = [book for book in self.books if title.lower() in book.lower()]
if found_books:
print("Matching books found:")
for book in found_books:
print(book)
else:
print(f"No books found matching '{title}'.")

INPUT

from library import Library

def main():
library = Library()

while True:
print("\nMenu:")
print("1. Add Book")
print("2. Remove Book")
print("3. Display Books")
print("4. Search Book")
print("5. Quit")

choice = input("Enter your choice (1-5): ")

if choice == '1':
book = input("Enter the name of the book: ")
library.add_book(book)
elif choice == '2':
book = input("Enter the name of the book to remove: ")
library.remove_book(book)
elif choice == '3':
library.display_books()
elif choice == '4':
title = input("Enter the title of the book to search: ")
library.search_book(title)
elif choice == '5':
print("Thank you! see you again.")
break
else:
print("Invalid input. Please try again.")

if __name__ == "__main__":
main()
OUTPUT
ASSIGNMENT 2

INPUT

import tkinter as tk

# Dictionary containing username-password pairs


credentials = {
"john_doe": "password1",
"jane_smith": "password2",
"bob_jones": "password3",
"sarah_davis": "password4",
"mike_ross": "password5",
"emily_brown": "password6",
"david_clark": "password7",
"laura_lee": "password8",
"chris_evans": "password9",
"kate_jackson": "password10",
}

def check_login():
username = entry_username.get()
password = entry_password.get()

if username in credentials and credentials[username] == password:


result_label.config(text="Login Successful")
else:
result_label.config(text="Invalid Credentials")

root = tk.Tk()
root.title("Login Page")

label_username = tk.Label(root, text="Username:")


label_password = tk.Label(root, text="Password:")
entry_username = tk.Entry(root)
entry_password = tk.Entry(root, show="*")
login_button = tk.Button(root, text="Login", command=check_login)
result_label = tk.Label(root, text="")

label_username.grid(row=0, column=0)
label_password.grid(row=1, column=0)
entry_username.grid(row=0, column=1)
entry_password.grid(row=1, column=1)
login_button.grid(row=2, column=0, columnspan=2)
result_label.grid(row=3, column=0, columnspan=2)

root.mainloop()

OUTPUT

You might also like