Python Lab Manual-1
Python Lab Manual-1
Python Lab Manual-1
1.i) Write a python program that defines a matrix and prints the matrix.
Program:
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print("Matrix =", matrix)
OUTPUT:
Matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
(OR)
OUTPUT:
Input:
Enter the number of rows: 2
Enter the number of columns: 2
Enter the entries row wise:
56
78
Output:
56
78
Program:
OUTPUT:
Enter the size of the square matrix:
3
Enter elements for matrix X:
123
456
789
Enter elements for matrix Y:
987
654
321
Resultant matrix after addition:
10 10 10
10 10 10
10 10 10
Program:
OUTPUT:
Enter the size of the square matrix:
3
Enter elements for matrix X:
123
456
789
Enter elements for matrix Y:
987
654
321
Resultant matrix after multiplication:
30 24 18
84 69 54
138 114 90
2. How do you make a module? Give an example of construction of a module using different
geometrical shapes and operations on its functions.
A module is essentially a self-contained Python file that contains statements, functions, and
definitions.
In this example, the module defines two classes, Rectangle and Circle, each representing a geometrical
shape. Each class has methods to calculate the area and perimeter of the shape. The Rectangle class
takes width and height as parameters, while the Circle class takes the radius as a parameter. The math
module is used to access the value of π for the circle calculations.geometry.py
import math
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
Moduse.py
import geometry
rectangle = geometry.Rectangle(5, 3)
circle = geometry.Circle(4)
print("Rectangle:")
print("Area:", rectangle.area())
print("Perimeter:", rectangle.perimeter())
print("\nCircle:")
print("Area:", circle.area())
print("Perimeter:", circle.perimeter())
OUTPUT:
OUTPUT:
6. a)Write a function called draw rectangle that takes a Canvas and a Rectangle as
arguments and draws a representation of the Rectangle on the Canvas.
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.create_rectangle(10, 10, 100, 100, fill='blue')
root.mainloop()
OUTPUT:
Rectangle created
b)Add an attribute named color to your Rectangle objects and modify draw rectangles
that it uses the color attribute as the fill color.
OUTPUT:
Rectangle color changed.
c)Write a function called draw point that takes a Canvas and a Point as arguments and
draws are presentation of the Point on the Canvas.
OUTPUT:
d) Define a new class called Circle with appropriate attributes and instantiate a few
Circle objects Write a function called draw circle that draws circles on the canvas.
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))
plt.axis('scaled')
plt.show()
RedCircle = Circle(10, 'red')
RedCircle.radius
RedCircle.color
RedCircle.radius = 1
RedCircle.drawCircle()
BlueCircle = Circle(radius=100)
BlueCircle.radius
BlueCircle.color
BlueCircle.drawCircle()
OUTPUT:
circles created with both colors
6.2. Write a Python program to demonstrate the usage of Method Resolution Order(MRO) in multiple
levels of Inheritances.
Explanation:
Class D inherits from both B and C.The method rk() is overridden in classes B and C.When we create
an instance of D and call rk(), Python follows the Method Resolution Order (MRO) to execute the
method from class B.The MRO order for class D is: D -> B -> C -> A. Python uses a depth-first lookup
order, followed by left-to-right traversal in case of multiple inheritance.
Program:
class A:
def rk(self):
print("In class A")
class B(A):
def rk(self):
print("In class B")
class C(A):
def rk(self):
print("In class C")
OUTPUT:
In class B
6.3 Write a python code to read a phone number and email-Id from the user and
validate it for correctness
import re
def validate_phone_number(potential_number: str, country_code: str) -> bool: try:
phone_number_obj = phonenumbers.parse(potential_number, country_code) except
phonenumbers.phonenumberutil.NumberParseException: return False if not
phonenumbers.is_valid_number(phone_number_obj): return False return Truedef
validate_email(email: str) -> bool: pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return re.match(pattern, email) is not None
user_input = input("Enter a phone number: ")country_code = "91" # Replace with the appropriate
country code
if validate_phone_number(user_input, country_code):print("Valid phone number!")
else:print("Invalid phone number.")
user_email = input("Enter an email address: ")
if validate_email(user_email):print("Valid email address!")
else: print("Invalid email address.")
OUTPUT:
Week -7
1.write a python code to merge two given file contents into third file
# open the first input file and read its contents
with open('file1.txt', 'r') as file1:
contents1 = file1.read()
# open the second input file and read its ontents
with open('file2.txt', 'r') as file2:
contents2 = file2.read()
# combine the contents of the two files
merged_contents = contents1 + contents2
# open the output file and write the merged contents
with open('merged_file.txt', 'w') as merged_file:
merged_file.write(merged_contents)
Output:
Students for output, u have to create file1.txt,file2.txt and save files with some content. Later after
executing with execution command merged_file,txt is automatically created with both the contents of
file 1 and file2
2.write a python code to open a given file and construct a function to check for
given words present in in it and display on found
def check_words_in_file(filename, words_to_check):
# open the file and read its contents
with open(filename, 'r') as file:
contents = file.read()
3.write a python code to read text from a text file, find the word with most no.
of occurences
4.write a function that reads a file file1 and displays the number of
words ,number of vowels ,blankspaces, lower case letters and uppercase letters
def file_stats(filename):
# open the file and read its contents
with open(filename, 'r') as file:
contents = file.read()
# initialize counters
num_words = 0
num_vowels = 0
num_spaces = 0
num_lowercase = 0
num_uppercase = 0
OUTPUT:
Week-8
Import numpy, Plotpy and Scipy and explore their functionalities.
Installation commands:
NumPy is a Python library used for working with arrays,in domain of linear
algebra, fourier transform, and matrices. NumPy stands for Numerical Python.
sns.distplot(random.normal(size=1000), hist=False)
plt.show()
OUTPUT:
Program:
import spacyfrom scipy import statsdata1 = [1, 2, 3, 4, 5]data2 = [2, 3, 4, 5,
6]t_statistic, p_value = stats.ttest_ind(data1, data2)if p_value < 0.05:
print("The means of the two datasets are significantly different.")else:
print("The means of the two datasets are not significantly
different.")OUTPUT:
C)Plotting data read from a fileInstallation:
Pip install matplotlib
Program:
from matplotlib import pyplot as pltplt.rcParams["figure.figsize"] = [7.00,
3.50]plt.rcParams["figure.autolayout"] = Truebar_names = []bar_heights =
[]for line in open("path of file12.txt/file12.txt", "r"): bar_name, bar_height =
line.split() bar_names.append(bar_name)
bar_heights.append(bar_height)plt.bar(bar_names,
bar_heights)plt.show()file12.txt:Javed 12Raju 14Rishi 15Kiran 10Satish
17Arun 23
OUTPUT:
print("Mean:", mean)
print("Standard Deviation:", std_dev)
print("Maximum value:",max_value)
arr2d=np.array([[1,2,3],[3,4,5]])
print("2D array:",arr2d)
sum_axis0=np.sum(arr2d,axis=0)
sum_axis1=np.sum(arr2d,axis=1)
print("Sum along axis 0 :", sum_axis0)
print("Sum along axis 1 :", sum_axis1)
OUTPUT:
b) Plot a histogram of words according to their length from text read from a
file.
Program:
# main function
if __name__=='__main__':
print(AND(0,0))
print(AND(1,0))
print(AND(0,1))
print(AND(1,1))
# main function
if __name__=='__main__':
print(NOR(0,0))
print(NOR(1,0))
print(NOR(0,1))
print(NOR(1,1))
# main function
if __name__=='__main__':
print(NAND(0,0))
print(NAND(1,0))
print(NAND(0,1))
print(NAND(1,1))
def NOT(a):
if(a == 0):
return 1
elif(a == 1):
return 0
# main function
if __name__=='__main__':
print(OR(0))
print(OR(1))
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
def halfAdder(a,b):
sum_o=XOR_gate(a,b)
carry_o=AND_gate(a,b)
return sum_o,carry_o
def full_adder(a,b,cin):
sum_o1,carry_o1=halfAdder(a,b)
sum_o2,carry_o2=halfAdder(sum_o1,cin)
carry_ot=OR_gate(carry_o1,carry_o2)
return sum_o2,carry_ot
def parallelAdder(a,b):
n=len(a)
sum_o=[]
carry_bit=0
for i in range(n-1,-1,-1):
sum_bit,carry_bit=full_adder(a[i],b[i],carry_bit)
sum_o.insert(0,sum_bit)
return sum_o,carry_bit
def AND_gate(a,b):
if(a==1 and b==1):
return 1
else:
return 0
def OR_gate(a,b):
if(a==1 or b==1):
return 1
else:
return 0
def XOR_gate(a,b):
if(a!=b):
return 1
else:
return 0
a=[1,0,1,1]
b=[1,1,0,1]
sum_ha,carry_ha=halfAdder(a[0],b[0])
print("Half Adder:")
print("sum:",sum_ha)
print("carry:",carry_ha)
print()
sum_fa,carry_fa=full_adder(a[0],b[0],0)
print("Full Adder:")
print("sum:",sum_fa)
print("carry:",carry_fa)
print()
sum_pa,carry_pa=parallelAdder(a,b)
print("Parallel Adder:")
print("sum:",sum_pa)
print("carry:",carry_pa)
print()
5. Write a GUI program to create a window wizard having two text labels, two
text fields and two buttons as Submit and Reset.import tkinter as tkdef
submit():print("Submitted")print(entry1.get())print(entry2.get())def reset(): #
Function to handle the reset button click # Clears the content of the text fields
entry1.delete(0, tk.END) entry2.delete(0, tk.END)# Create the main
windowroot = tk.Tk()root.title("Window Wizard")# Create labelslabel1 =
tk.Label(root, text="Label 1:")label1.grid(row=0, column=0, padx=10,
pady=5)label2 = tk.Label(root, text="Label 2:")label2.grid(row=1, column=0,
padx=10, pady=5)# Create text fieldsentry1 = tk.Entry(root)entry1.grid(row=0,
column=1, padx=10, pady=5)entry2 = tk.Entry(root)entry2.grid(row=1,
column=1, padx=10, pady=5)# Create buttonssubmit_button = tk.Button(root,
text="Submit", command=submit)submit_button.grid(row=2, column=0,
padx=10, pady=5, sticky="we")reset_button = tk.Button(root, text="Reset",
command=reset)reset_button.grid(row=2, column=1, padx=10, pady=5,
sticky="we")# Start the GUI event looproot.mainloop()