PYTHON LAB FILE
Program 1: WAP to print Pythagorean triplets
Solution: #TO PRINT PYTHAGOREAN TRIPLETS
limit=int(input("Enter upper limit")) c=0
m=2
while(c<limit):
for n in range(1,m+1):
a=m*m-n*n
b=2*m*n
c=m*m+n*n
if(c>limit):
break
if(a==0 or b==0 or c==0):
break
print(a,b,c)
m=m+1
Output:
Program 2: WAP to print reverse of number
Solution:
n=int(input("enter number")) rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print ("Reverse of number is: ",rev)
Output:
Program 3: Check if a Number is an Armstrong Number
Solution:
num=int(input("Enter a number")) sum=0
#Intialise the sum with zero temp=num
while temp>0:
digit=temp%10
sum=sum+(digit**3)
temp//=10
if(num==sum):
print(num,"Armstrong number") else:
print(num,"Not Armstrong number")
Output:
Program 4: Print “n” Natural Numbers
Solution:
number=int(input("Please enter number"))
print("The list of natural numbers from 1 to {0}are".format(number))
for i in range(1,number +1):
print(i,end=’ ’)
Output:
Program 5: Remove Vowels and Punctuation
Solution:
punctuations="'!()-[];:"'\,<>./?@#$%^&*_~"'
my_str="Hello !!!,he said ---and ran"
no_punct=""
for char in my_str:
if char not in punctuations:
no_punct=no_punct+char
print(no_punct)
Output:
Program 6: Count the number of strings
Solution:
count = 0
stri = "Programming"
char='r'
for i in stri:
if i == char:
count = count + 1
print(char, "repeats :", count, "times")
Output:
Program 7: Tuple Sorting
Solution:
Y=(5,9,1,7,19,25,18,12)
T=sorted(Y)
print(tuple(T))
Output:
Program 8: List Generation
Solution:
#program for list generation
L1=["abc",18,"uttar pradesh","male","playing games"]
print(L1[0])
print(L1[2])
#Slicing
print(L1[0:1])
print(L1[:])
print(L1[1:3])
print(L1[1:4:2])
#Updating list L1[1]=40
[Link]("We") print(L1)
#Adding multiple elements
L1[1:3]=[10,14]
print(L1)
#list operations
print(L1*2)
print(L1+L1)
Output:
Program 9: Merge dictionaries
Solution:
dict1={"Meemansa":18,"Aniruddh":8,"Beena":42}
dict2={"Ashi":12,"Abhi":15} [Link](dict2)
print("Updated dictionary",dict1)
Output:
Program 10: Convert a roman numeral to an integer
Solution:
def roman_to_int(roman):
# Dictionary to map Roman numerals to integers
roman_values = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
# Initialize the integer value
total = 0
prev_value = 0
# Process each character in the Roman numeral string from right to left
for char in reversed(roman):
# Get the integer value of the current Roman numeral character
current_value = roman_values[char]
# If the current value is less than the previous value, subtract it from the
total
if current_value < prev_value:
total -= current_value
# Otherwise, add it to the total
else:
total += current_value
# Update the previous value for the next iteration
prev_value = current_value
return total
roman_numeral = "MCMXCVII"
integer_value = roman_to_int(roman_numeral)
print(f"The integer value of the Roman numeral {roman_numeral} is
{integer_value}")
Output:
Program 11: Calculate student Grades
Solution:
sub1 = int(input("Enter marks in subject 1 out of 100:")) sub2 =
int(input("Enter marks in subject 2 out of 100:")) sub3 =
int(input("Enter marks in subject 3 out of 100:")) sub4 =
int(input("Enter marks in subject 4 out of 100:")) sub5 =
int(input("Enter marks in subject 5 out of 100:")) total = sub1 +
sub2 + sub3 + sub4 + sub5 per = total / 5 if per > 90:
print("Grade A") elif per < 90
and per >= 80:
print("Grade B") elif per < 80
and per >= 70:
print("Grade C") elif per <
70:
print("Grade D") else:
print("fail")
Output:
Program 12: Create Address Book
Solution:
class Contact:
def __init__(self, name, phone, email, address):
[Link] = name
[Link] = phone
[Link] = email
[Link] = address
def __str__(self):
return f"Name: {[Link]}, Phone: {[Link]}, Email: {[Link]},
Address: {[Link]}"
class AddressBook:
def __init__(self):
[Link] = []
def add_contact(self, name, phone, email, address):
new_contact = Contact(name, phone, email, address)
[Link](new_contact)
print(f"Contact {name} added successfully.")
def remove_contact(self, name):
for contact in [Link]:
if [Link] == name:
[Link](contact)
print(f"Contact {name} removed successfully.")
return
print(f"Contact {name} not found.")
def display_contacts(self):
if not [Link]:
print("Address book is empty.")
else:
for contact in [Link]:
print(contact)
def main():
address_book = AddressBook()
while True:
print("\nAddress Book Menu:")
print("1. Add Contact")
print("2. Remove Contact")
print("3. Display Contacts")
print("4. Exit")
choice = input("Choose an option: ")
if choice == '1':
name = input("Enter name: ")
phone = input("Enter phone number: ")
email = input("Enter email: ")
address = input("Enter address: ")
address_book.add_contact(name, phone, email, address)
elif choice == '2':
name = input("Enter name of the contact to remove: ")
address_book.remove_contact(name)
elif choice == '3':
address_book.display_contacts()
elif choice == '4':
print("Exiting Address Book. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Output:
Program 13: Implement Calculator
Solution:
#Calculator
num1= float(input("enter number
1"))
num2 =float(input("enter number 2"))
operator=input("enter operator") if(operator=='+'):
print(num1+num2)
elif(operator=='-'):
print(num1-num2)
elif(operator=='*'):
print(num1*num2)
elif(operator=='/'):
print(num1/num2)
else:
print("Inavlid Operator")
Output:
Program 14: Greatest Common Divisor (GCD)
Solution:
#WAP to find greatest common divisor(GCD)
#import math library
import math
#find the greatest commom=n divisor of the two integers
print([Link](3,6))
print([Link](6,12))
print([Link](12,36))
print([Link](-12,-36))
print([Link](5,12))
print([Link](10,0))
print([Link](0,34))
print([Link](0,0))
Output:
Program 15: Expression Evaluation
Solution:
# basic arithmetic
print(eval("3 ** 2"))
print(eval("sum([1, 2, 3, 4])"))
x=2
# mathematical expression with local variable a and global variable x
print(eval("x ** 2 + a", {"x": x},{"a": 20}))
Output:
Program 16: Dictionary Grouping
Solution:
#Wap to Dictionary Grouping
#initializing Dictionary
test_dict={'gfg1':1,'is1':2,'best1':3,
'gfg2':9,'is2':8,'best2':7,
'gfg3':10,'is3':5,'best3':6}
#printing original dictionary
print("The original dictionary is:"+str(test_dict))
#group similar keys in dictionary
#using dictionary
res=[]
res1={key:val for key,val in test_dict.items() if 'gfg' in key}
res2={key:val for key,val in test_dict.items() if 'is' in key}
res3 = {key : val for key, val in test_dict.items() if 'best' in key}
[Link](res1)
[Link](res2)
[Link](res3)
# printing result
print("The grouped similar keys are : " + str(res))
Output:
Program 17: Machine Value Conversion
Solution:
# declaring an integer value
integer_val = 5
# converting int to bytes with length
# of the array as 2 and byter order as big
bytes_val = integer_val.to_bytes(2, 'big')
# printing integer in byte representation
print(bytes_val)
Output:
Program 18: GUI using Tk Interface
Solution:
#Program for GUI
import tkinter
window =[Link]()
l1=[Link](window,text=' Welcome to Tkinter !!',font=('calibri
bold',70),bg="green",fg="yellow")
[Link]()
[Link]()
Output:
Program 19: Calculator - GUI
Solution:
# Python program to create a simple GUI
# calculator using Tkinter
# import everything from tkinter module
from tkinter import *
# create a GUI window
gui = Tk()
# set the background colour of GUI window
[Link](background="light green")
# set the title of GUI window
[Link]("Simple Calculator")
# set the configuration of GUI window
[Link]("270x150")
# set the menu of GUI window
menu = Menu(gui)
[Link](menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=[Link])
Editmenu = Menu(menu)
menu.add_cascade(label='Edit', menu=Editmenu)
Editmenu.add_command(label='Edit')
47
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
# globally declare the expression variable
expression = ""
# Function to update expression in the text entry box
def press(num):
# point out the global expression variable
global expression
# concatenation of string
expression = expression + str(num)
# update the expression by using set method
[Link](expression)
# Function to evaluate the final expression
def equalpress():
# Try and except statement is used
# for handling the errors like zero division error etc.
# Put that code inside the try block
# which may generate the error
try:
global expression
# eval function evaluate the expression
# and str function convert the result
# into string
total = str(eval(expression))
[Link](total)
# initialize the expression variable
# by empty string
expression = ""
# if error is generate then handle by the except block
except:
[Link](" error ")
expression = ""
# Function to clear the contents of text entry box
def clear():
global expression
expression = ""
[Link]("")
48
# create a GUI window
gui = Tk()
# set the background colour of GUI window
[Link](background="light green")
# set the title of GUI window
[Link]("Simple Calculator")
# set the configuration of GUI window
[Link]("270x150")
# StringVar() is the variable class
# we create an instance of this class
equation = StringVar()
# create the text entry box for
# showing the expression .
expression_field = Entry(gui, textvariable=equation)
# grid method is used for placing
# the widgets at respective positions
# in table like structure .
expression_field.grid(columnspan=4, ipadx=70)
# create a Buttons and place at a particular
# location inside the root window .
# when user press the button, the command or
# function affiliated to that button is executed .
button1 = Button(gui, text=' 1 ', fg='black', bg='red', command=lambda:
press(1), height=1,
width=7)
[Link](row=2, column=0)
button2 = Button(gui, text=' 2 ', fg='black', bg='red', command=lambda:
press(2), height=1,
width=7)
[Link](row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='red', command=lambda:
press(3), height=1,
width=7)
[Link](row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='red', command=lambda:
press(4), height=1,
width=7)
[Link](row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='red', command=lambda:
press(5), height=1,
width=7)
49
[Link](row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='red', command=lambda:
press(6), height=1,
width=7)
[Link](row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='red', command=lambda:
press(7), height=1,
width=7)
[Link](row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='red', command=lambda:
press(8), height=1,
width=7)
[Link](row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='red', command=lambda:
press(9), height=1,
width=7)
[Link](row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='red', command=lambda:
press(0), height=1,
width=7)
[Link](row=5, column=0)
plus = Button(gui, text=' + ', fg='black', bg='red', command=lambda:
press("+"), height=1,
width=7)
[Link](row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='red', command=lambda: press("-
"), height=1,
width=7)
[Link](row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='red', command=lambda:
press("*"), height=1,
width=7)
[Link](row=4, column=3)
divide = Button(gui, text=' / ', fg='black', bg='red', command=lambda:
press("/"), height=1,
width=7)
[Link](row=5, column=3)
equal = Button(gui, text=' = ', fg='black', bg='red', command=equalpress,
height=1, width=7)
[Link](row=5, column=2)
50
clear = Button(gui, text='Clear', fg='black', bg='red', command=clear,
height=1, width=7)
[Link](row=5, column='1')
Decimal= Button(gui, text='.', fg='black', bg='red', command=lambda:
press('.'), height=1,
width=7)
[Link](row=6, column=0)
# start the GUI
[Link]()
Output:
Program 20: OS Module – System Services
Solution:
1) [Link]()
import os
print([Link])
Output:
2) [Link]( ) (Getting Current Working Directory)
import os
[Link]( )
output:
3) [Link]() (Creating a Directory)
import os
[Link]("C:\MyPythonProject")
4) [Link]( ) (Changing the Current Working Directory)
Change Directory to Drive
Change CWD to Parent
5)
[Link]( )(Removing a Directory)
Remove Directory
6) os. listdir() (List Files and Sub-directories)
The listdir() function returns the list of all files and directories in the specified
directory.
54
Example: List Directories
Example: List Directories of CWD
7)
[Link]()
import os
fd = "[Link]"
[Link](fd,'[Link]')
8) [Link]()
import os
fr = "[Link]"
file = open(fr, 'r')
text = [Link]()
print(text)
[Link](file)
9) [Link]
import os
output = [Link]['HOME']
print(output)
Program 21: OS Module – File Services
Solution:
1) [Link]()
import os
fd = "[Link]"
file = open(fd, 'w')
[Link]("This is awesome")
[Link]()
file = open(fd, 'r')
text = [Link]()
print(text)
file = [Link](fd, 'w')
[Link]("This is awesome")
2) [Link]()
import os
fr = "[Link]"
file = open(fr, 'r')
text = [Link]()
print(text)
[Link](file)
Program 22: Array operations – Numpy
Solution:
NumPy Array Creation
1. Using the NumPy functions
a. Creating one-dimensional array in NumPy
import numpy as np
array=[Link](20)
array
[Link]
array[3]
b. Creating two-dimensional arrays in NumPy
array=[Link](20).reshape(4,5)
c. Using other NumPy functions
[Link]((2,4))
[Link]((3,6))
[Link]((2,3))
[Link]((2,2), 3)
[Link](3,3)
[Link](0, 10, num=4)
2. Conversion from Python structure like lists
array=[Link]([4,5,6])
array
list=[4,5,6]
list
3. Using other library functions
[Link]((2,3))
Checking Array Dimensions in NumPy
import numpy as np
a = [Link](10)
b = [Link]([1,1,1,1])
c = [Link]([[1, 1, 1], [2,2,2]])
d = [Link]([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
print([Link])
print([Link])
print([Link])
print([Link])
Higher Dimensional Arrays in NumPy
import numpy as np
arr = [Link]([1, 1, 1, 1, 1], ndmin=10)
print(arr)
print('number of dimensions :', [Link])
Indexing in NumPy
import numpy as np
arr=([1,2,5,6,7])
arr[3]
Slicing in NumPy
import numpy as np
arr=([1,2,5,6,7])
arr[2:5]
Program 23: Charts – Matplotlib
Solution: [Link] a Bar Chart in Python using Matplotlib
import [Link] as plt
country = ['A', 'B', 'C', 'D', 'E']
gdp_per_capita = [45000, 42000, 52000, 49000, 47000]
[Link](country, gdp_per_capita)
[Link]('Country Vs GDP Per Capita')
[Link]('Country')
[Link]('GDP Per Capita')
[Link]()
b. Create a Pie Chart using Matplotlib
import [Link] as plt
my_data = [300, 500, 700]
my_labels = 'Tasks Pending', 'Tasks Ongoing', 'Tasks Completed'
[Link](my_data, labels=my_labels, autopct='%1.1f%%')
[Link]('My Tasks')
[Link]('equal')
[Link]()
c. Create a Scatter Diagram in Python using Matplotlib
import [Link] as plt
unemployment_rate = [6.1, 5.8, 5.7, 5.7, 5.8, 5.6, 5.5, 5.3, 5.2, 5.2]
index_price = [1500, 1520, 1525, 1523, 1515, 1540, 1545, 1560, 1555, 1565]
[Link](unemployment_rate, index_price, color='green')
[Link]('Unemployment Rate Vs Index Price', fontsize=14)
[Link]('Unemployment Rate', fontsize=14)
[Link]('Index Price', fontsize=14)
[Link](True)
[Link]()
d. Plot a Line Chart in Python using Matplotlib
import [Link] as plt
year = [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010]
unemployment_rate = [9.8, 12, 8, 7.2, 6.9, 7, 6.5, 6.2, 5.5, 6.3]
[Link](year, unemployment_rate)
[Link]('unemployment rate vs year')
[Link]('year')
[Link]('unemployment rate')
[Link]()
e. Histograms
from matplotlib import pyplot as plt
import numpy as np
fig,ax = [Link](1,1)
a = [Link]([12,80,30,65,60,73,55,54])
[Link](a,bins='auto')
ax.set_title("HISTOGRAM")
ax.set_xlabel("MARKS")
ax.set_ylabel("STUDENTS")
[Link]()
f. Matplotlib Subplots
from matplotlib import pyplot as plt
[Link](1,2,1)
[Link]([1,2,3],[3,2,2])
[Link]("1st subplot")
[Link](1,2,2)
[Link]([2,3,3],[3,2,2],"r^")
[Link]("2nd subplot")
[Link]()
Program 24: File Operation on Excel
Solution:
Program 25: WAP to check for roots of a quadratic equation
Solution:
def quadratic_equation(a,b,c):
D=(b**2)-4*a*c
if(D==0):
print("Real and roots are repetitive")
elif(D<0):
print("Complex numbers")
else:
x1=(-b+((D)**(1/2)))/2*a
x2=(-b-((D)**(1/2)))/2*a
print("Real and distinct roots are:",x1," ",x2)
quadratic_equation(1,7,9)
Program 26: Write a Program to remove duplicate
elements from the list
Solution:
#To remove duplicate elements from the list
list1=[1,2,3,4,4,5,5,6,7]
list2=[]
for i in list1: if i not in list2: [Link](i)
print(list2)
Output:
Program 27: Write a Program to find sum of all
elements in the list
Solution:
#Sum of all elements in the list list1=[1,3,5,2,6] sum=0 for i
in list1:
sum=sum+i
print(sum)
Output:
Program 28: Write a Program to print Calendar
Solution:
import calendar
yy=2023
print([Link](yy))
Output:
Program 29: Write a Program for Regular Expression
Solution:
#program for regular expression
import re pattern="Hello I "
text=" Hello I am Meemansa [Link] hobby is reading
books."
result=[Link](pattern,text)
print(result)
Output:
B) import re pattern="Hello"
text="My name is Meemansa sharma"
print([Link]('is',text))
print(result)
Output:
Program 30: Write a Program to make a message box using
Tkinter GUI
Solution:
#MESSAGE BOX USING TKINTER
GUI
import tkinter from tkinter
import messagebox
m=[Link]()
def fun():
[Link]("Click","Hello")
b=[Link](m,text="hello",command=fun)
[Link]()
b=[Link](m,text="Bye",command=[Link])
[Link]()
[Link]()
Output:
Program 31: Write a Program to make a file manager using
GUI(Tkinter)
Solution:
#file manager
#importing those functions which are needed
from tkinter import *
from [Link] import *
from time import strftime
#Creating tkinter window
root=Tk()
[Link]('Menu Demonstration')
#Creating menubar
menubar=Menu(root)
#Adding File Menu and commands
file= Menu(menubar,tearoff=0)
menubar.add_cascade(label='File',menu=file)
file.add_command(label="New File",command=None)
file.add_command(label='Open',command=None)
file.add_command(label="Save",command=None)
file.add_separator()
[Link](menu=menubar)
mainloop()
#Adding edit menu and command
Edit=Menu(menubar,tearoff=0)
menubar.add_cascade(label="Edit",menu=Edit)
menubar.add_cascade(label='Cut',menu=file)
edit.add_command(label="Copy",command=None)
edit.add_command(label="Paste",command=None)
edit.add_command(label="SelectAll",command=None)
[Link](menu=menubar) mainloop()
Output:
Program 32: Write a Program to implement stacks
Solution:
#To implement stack stack=[]
[Link](1)
[Link](2)
[Link](3)
[Link](4)
print(stack)
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print("stacks after elements popped")
print(stack)
Output:
Program 33: Write a Program to implement queue
Solution:
#Program for queue
queue=[]
[Link](1)
[Link](2)
[Link](3)
print(queue)
[Link](0)
[Link](0)
[Link](0)
print("Queue after elements are
removed")
print(queue)
Output:
Program 34: Write a Program to implement list
comprehension
Solution:
#List comprehension
list1=[2,4,6,8]
list2=[]
for n in list1:
[Link](n**2)
print(list2)
Output:
Program 35: Write a Program to implement Traditional
approach Solution:
#traditional approach
list=[]
for character in 'traditional approach':
[Link](character)
print(list)
Output:
Program 36: Write a Program to implement matrix operation
Solution:
#matrix operation
matrix=[]
for i in range (6):
[Link]([])
for j in range(2):
matrix[i].append(j)
print(matrix)
Output:
Program 37: Write a Program to implement Dictionary
Elements through loop statement
Solution:
#enter dictionary elements through loop statements
dict1={'a':10,'b':20,'c':30,'d':40}
print("dictionary elements through loop
statements:")
for k,v in [Link]():
print(f'{k}={v}')
print("dictionary elements")
Output:
Program 38: Write a Program to implement Compression
using zip
Solution: #compression using zip
list1=[1,2,3,4,5]
list2=[6,7,8,9,10]
dict1=dict(zip(list1,list2))
print(dict1)
Output:
Program 39: Write a Program to implementation of pickle
library to print data Solution:
#IMPPLEMENTATION OF PICKLE
LIBRARY
import pickle
mylist=['a','b','c','d']
with open("[Link]",'wb')as fh:
[Link](mylist,fh)
pickle_off=open("[Link]",'rb')
data=[Link](pickle_off)
print(data)
Output:
Program40: Write a Program to implement lambda square
with dill and pickle library
Solution:
#Lambda square with dill and pickle
library
import dill square=lambda X:x*x
my_pickle=[Link](square)
print(my_pickle)
Output:
Program 41: Write a Program to implement keyboard
Solution:
import keyword
print([Link])
Output: