Python Programs Final
Python Programs Final
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.
Program 1.1:
Basic data types, Operators, expressions and Input Output 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:
OUTPUT:
INPUT
OUTPUT
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
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
OUTPUT
EXPERIMENT 1.1.7 A :ASSIGNMENT OPERATORS
INPUT
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
INPUT
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
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
OUTPUT
INPUT
number=input('enter number:')
if int(number)>0:
print('number is positive')
else:
print('number is negative')
OUTPUT
INPUT
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
INPUT
OUTPUT
<<< Copy Source Code and Paste Output >>>
Program 1.3:
Looping in Python (while loop, for loop, nested loops)
INPUT
OUTPUT
EXAMPLE 2
INPUT
OUTPUT
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
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
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
INPUT
OUTPUT
ASSIGNMENT
INPUT
print("Taran kaur valecha_D2B_60")
OUTPUT
Program 1.4: Decorators, Iterators and Generators
EXPERIMENT 1.4.1
INPUT
OUTPUT
INPUT
OUTPUT
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
OUTPUT
Program 2.1:
Different List and Tuple operations using Built-in functions
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')
Output
Experiment 2.1.3
Input
Output
Exp 2.1.4
Input
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
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
#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)
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
Output
Exp 2.4.3
Input
print("Taran Kaur valecha_D2B_60")
Output
Exp 2.4.4
Input
print("Taran Kaur Valecha_D2B_60")
ages = [13,90,17,59,21,60,5]
adults = list(filter(lambda age: age>18, ages))
print(adults)
Output
ASSIGNMENT
INPUT
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"
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"
Output
Experiment 3.1.3
Input
print("Tarankaurvalecha_D2B_60")
# create a class
class room:
length = 0.0
breadth = 0.0
def calculate_area(self):
print ("area of room= ", self.length* self.breadth)
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")
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")
OUTPUT
ASSIGNMENT
PASSWORD GENERATOR
INPUT
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
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
INPUT
OUTPUT
EXP 4.1.2
PACKAGE FILE
class Student:
def get_student_details(self):
return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}"
class Faculty:
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
t1.join()
t2.join()
print("bye")
OUTPUT
EXP 4.2.2
INPUT
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()
OUTPUT
Program 4.3
Creating a menu driven application which should cover all the built-in exceptions
in
python
INPUT
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
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
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
OUTPUT
EXP 5.2.2
Input
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.
Exp 6.1.1
Input
import tkinter as tk
import sqlite3
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"]
INPUT
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")
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
def check_login():
username = entry_username.get()
password = entry_password.get()
root = tk.Tk()
root.title("Login Page")
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