0% found this document useful (0 votes)
12 views32 pages

Python Lab Manual (AVN)-1

The document outlines a Python programming laboratory course for B.Tech. students, detailing course objectives, outcomes, and a structured lab schedule over 16 weeks. It includes various programming exercises focused on Python fundamentals such as control structures, data types, file handling, and digital systems implementation. Additionally, it lists textbooks and reference materials to support the course content.

Uploaded by

uppulurisatya16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
12 views32 pages

Python Lab Manual (AVN)-1

The document outlines a Python programming laboratory course for B.Tech. students, detailing course objectives, outcomes, and a structured lab schedule over 16 weeks. It includes various programming exercises focused on Python fundamentals such as control structures, data types, file handling, and digital systems implementation. Additionally, it lists textbooks and reference materials to support the course content.

Uploaded by

uppulurisatya16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 32

PYTHON PROGRAMMING LABORATORY

B.Tech. I Year II Sem. L T P C

0 1 2 2
Course Objectives:

 To install and run the Python interpreter


 To learn control structures.
 To Understand Lists, Dictionaries in python
 To Handle Strings and Files in Python

Course Outcomes: After completion of the course, the student should be able to

● Develop the application specific codes using python.


● Understand Strings, Lists, Tuples and Dictionaries in Python
● Verify programs using modular approach, file I/O, Python standard library
● Implement Digital Systems using Python
Note: The lab experiments will be like the following experiment examples

Week -1&2:
1. i) Use a web browser to go to the Python website http://python.org. This page contains
information about Python and links to Python-related pages, and it gives you the ability to
search the Python documentation.
ii) Start the Python interpreter and type help() to start the online help utility.
2. Start a Python interpreter and use it as a Calculator.
3.
i) Write a program to calculate compound interest when principal, rate and number of periods
are given.
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
4. Read name, address, email and phone number of a person through keyboard and print the details.

Week – 3&4:
1. Print the below triangle using for loop.
5
44
333
2222
11111
2. Write a program to check whether the given input is digit or lowercase character or
upper case character or a special character (use 'if-else-if' ladder)
3. Python Program to Print the Fibonacci sequence using while loop
4. Python program to print all prime numbers in a given interval (use break)

Week – 5&6:
1. i) Write a program to convert a list and tuple into arrays.
ii) Write a program to find common values between two arrays.
2. Write a function called gcd that takes parameters a and b and returns their greatest common
divisor.
3. Write a function called palindrome that takes a string argument and returns True if it is a
Palindrome and False otherwise. Remember that you can use the built-in function len to check the
length of a string.

Week – 7&8:
1. Write a function called is_sorted that takes a list as a parameter and returns True if the list is
sorted in ascending order and False otherwise.
2. Write a function called has_duplicates that takes a list and returns True if there is any element
that appears more than once. It should not modify the original list.
i). Write a function called remove_duplicates that takes a list and returns a new list with only
the unique elements from the original. Hint: they don’t have to be in the same order.
ii). The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want to
add“I”, “a”, and the empty string.
iii). Write a python code to read dictionary values from the user. Construct a function to invert
its content. i.e., keys should be values and values should be keys.
3. i) Add a comma between the characters. If the given word is 'Apple', it should become 'A,p,p,l,e'
ii) Remove the given word in all the places in a string?
iii) Write a function that takes a sentence as an input parameter and replaces the first letter of
every word with the corresponding upper case letter and the rest of the letters in the word by
corresponding letters in lower case without using a built-in function?
4. Writes a recursive function that generates all binary strings of n-bit length

Week – 9&10:
1. i) Write a python program that defines a matrix and prints
ii) Write a python program to perform addition of two square matrices
iii) Write a python program to perform multiplication of two square matrices
2. How do you make a module? Give an example of construction of a module using different
geometrical shapes and operations on them as its functions.
3. Use the structure of exception handling all general purpose exceptions.

Week-11&12:
1. 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.
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle so
that it uses the color attribute as the fill color.
c. Write a function called draw_point that takes a Canvas and a Point as arguments and draws
arepresentation of the Point on the Canvas.
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.
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in
multiplelevels of Inheritances.
3. Write a python code to read a phone number and email-id from the user and validate it
forcorrectness.

Week- 13&14:
1. Write a Python code to merge two given file contents into a third file.
2. Write a Python code to open a given file and construct a function to check for given words
present init and display on found.
3. Write a Python code to Read text from a text file, find the word with most number of occurrences
4. Write a function that reads a file file1 and displays the number of words, number of vowels,
blank spaces, lower case letters and uppercase letters.

Week – 15&16:
1. Import numpy, Plotpy and Scipy and explore their functionalities.
2. a) Install NumPy package with pip and explore it.
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
5. Write a GUI program to create a window wizard having two text labels, two text fields and two
buttonsas Submit and Reset
TEXT BOOKS:
1. Supercharged Python: Take your code to the next level, Overland
2. Learning Python, Mark Lutz, O'reilly

REFERENCE BOOKS:
1. Python Programming: A Modern Approach, Vamsi Kurama, Pearson
2. Python Programming A Modular Approach with Graphics, Database, Mobile, and Web
Applications, Sheetal Taneja, Naveen Kumar, Pearson
3. Programming with Python, A User’s Book, Michael Dawson, Cengage Learning, India
Edition
4. Think Python, Allen Downey, Green Tea Press
5. Core Python Programming, W. Chun, Pearson
6. Introduction to Python, Kenneth A. Lambert, Cengage
WEEK-1&2:
1. (i) Use a web browser to go to the Python website http://python.org. This page
contains information about Python and links to Python-related pages, and it gives
you the ability to search the Python documentation.

Output:
import webbrowser
open('http://www.python.or
g')

1. (ii) Start the Python interpreter and type help() to start


theonline help utility.

help()

Output:
Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the internet at https://docs.python.org/3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type


"modules", "keywords", "symbols", or "topics". Each module also
comeswith a one-line summary of what it does; to list the modules whose
name or summary contain a given string such as "spam", type "modules
spam".

2. Start a Python interpreter and use it as

Calculator. CODE:
first = input("Enter first number : ")
second = input("Enter second number :
")first = int(first)
second = int(second)
print("----press keys for operator (+,-,*,/,%)--------- ")
operator = input("Enter operator :
") if operator == "+":
print(first + second)
elif operator == "-":
print(first -
second)
elif operator == "*":
print(first * second)
elif operator == "/":
print(first /
second)
elif operator == "%":
print(first %
second)
else:
print("Invalid Operation")

OUT PUT:
Enter first number : 4
Enter second number : 5
----press keys for operator (+,-,*,/,%)
Enter operator : *
20
3. (i) Write a program to calculate compound interest when principal, rate and
numbers o f p e ri od s a re given.

p = float(input("Enter the principal amount :


"))t = float(input("Enter the number of years
: "))
r = float(input("Enter the rate of interest : "))

amt= p * (pow((1 + r / 100),


t)) ci=amt-p

print("Compound interest", ci)


OUT PUT:
Enter the principal amount: 50000
Enter the annual interest rate (as a decimal): 0.025
Enter the number of periods (years): 2

Compound Interest after 2 years: 2531.25

3. (ii)Given coordinates (x1, y1), (x2, y2) find the distance between
twopoints.
x1=int(input("enter x1 :
")) x2=int(input("enter x2
: ")) y1=int(input("enter
y1 : "))
y2=int(input("enter y2 :
"))

result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)


print("distance between",(x1,x2),"and",(y1,y2),"is : ", result)

out put:
enter x1 : 5
enter x2 : 8
enter y1 : 7
enter y2 : 5
distance between (5, 8) and (7, 5) is : 3.605551275463989
4. Read name, address, email and phone number of a person through keyboard
and print the details.
print("Enter your name: ")
name = input()
print("Enter your phone number: ")
ph_num = input()
print("Enter your email: ")
email = input()
print("Enter your address: ")
address = input()

print("Name: ", name)


print("Phone Number: ", ph_num)
print("Email: ", email)
print("Address: ", address)
out put:
Enter the name:
Enter the address:
Enter the email address:
Enter the phone number:

Details:
Name:
Address:
Email:
Phone Number:

WEEK-3&4:
1. Print the below triangle using for loop.5

44
333
2222
11111

for i in range(4,0,-1):
for j in range(i,6):
print(i, end=””)
print(i)
Output:
44
333
2222
11111

2. Write a program to check whether the given input is digit or lowercase


characteror uppercase character or a special character (use 'if-else-if' ladder).
ch = input("Please Enter Your Own Character : ")
if (ch.isupper()):

print("The Given Character ", ch, "is an Uppercase Alphabet")


elif (ch.islower()):
print("The Given Character ", ch, "is a Lowercase Alphabet")
else:

print("The Given Character ", ch, "is Not a Lower or Uppercase Alphabet")
Output:

Enter a character: apple

apple is a lowercase character.

3. Python Program to Print the Fibonacci sequence using while loop.

terms = int(input("How many terms? "))


n1, n2 = 0, 1
count = 0

if terms <= 0:
print("Please enter a positive integer")
elif terms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,n2)
while count < terms-2:
nth = n1 + n2
print(nth)
n1=n2
n2 = nth
count += 1
Output:
How many terms? 9
Fibonacci sequence:
0 1 1 2 3 5 8 13 21

4. Python program to print all prime numbers in a given interval (use break).

lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) ==0:
break
else:
print(num)

Output:

Enter the start of the interval: 3


Enter the end of the interval: 90
Prime numbers between 3 and 90:
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
WEEK-5&6:
1. (i) Write a program to convert a list and tuple into arrays.

from array import array

test_list = [6, 4, 8, 9, 10]

print("The original list : "


+ str(test_list))

res = array("i", test_list)

print("List after
conversion to array : " +
str(res))

x = (6,4,8,9,10)
y = list(x)
print(y)

z = ((6,4,8), (9,10))
y = [a for b in z for a in
b]
print(y)
Output:
[2, 8, 4, 10, 5]
<class 'list'>
(11, 21, 19, 18, 46, 29)
<class 'tuple'>
converting Python list, tuple to array
by using np.asarray() function
[ 2 8 4 10 5]
[11 21 19 18 46 29]
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>

1. (ii) Write a program to find common values


between two arrays

a=[1,2,3,4]
b=[4,5,6,7]
print(set(a).intersection(set(b)))
Output:
<class 'numpy.ndarray'>
Common values between two arrays: [4]

2. Write a function called gcd that takes parameters a and b and returns their
greatest common divisor.

def computeGCD(x, y):

if x > y:
small = y
else:
small = x
for i in range(1, small + 1):
if((x % i == 0) and (y %
i == 0)):gcd = i
return gcd
a = 60
b = 48

print ("The gcd of 60 and 48 is :


", end="")
print (computeGCD(60,48))
Output:
The gcd of 60 and 48 is:12
12

3. Write a function called palindrome that takes a string argument and returns true if it is
a palindrome and false otherwise. Remember that you can use the built-in function len to
check the length of a string.

string=input(("Enter a letter:"))
if(string==string[::-1]):

print("The letter is a palindrome")


else:
print("The letter is not a palindrome")
Output:
Enter a letter: DAD
The letter is a palindrome
Week-7&8:
1. Write a function called is_sorted that takes a list as a parameter and returns True if
the list is sorted in ascending order and False otherwise

Source code:
def is_sorted(lst):
return all(lst[i] <= lst[i+1] for i in range(len(lst)-1))
print(is_sorted([5,4,3,2,1]))
Output:
before sort list is: [5,4,3,2,1]
after sort list is: [1, 2,3,4,5]
True

2. (i) Write a function called has_duplicates that takes a list and returns True if there
is any element that appears more than once. It should not modify the original list.

Source code:
def has_duplicates(lst):
unique_elements = set(lst)
return len(unique_elements) < len(lst)

print(has_duplicates([1, 2, 3, 4, 5]))
print(has_duplicates([1, 2, 3, 4, 4, 5]))
[if the list has duplicates it will give output as True, else it will give False]
i). Write a function called remove_duplicates that takes a list and returns a new list with
only the unique elements from the original. Hint: They don’t have to be in the same
order.

def remove_duplicates(lst):
unique_elements = set(lst)

unique_lst = list(unique_elements)
return unique_lst

lst = [1, 2, 3, 4, 4, 5]
unique_lst = remove_duplicates(lst)
print(unique_lst)

Output:
True
True
List is empty.
List contains only one element.
False

2.(ii). The wordlist I provided, words.txt, doesn’t contain single letter words. So you
might want to add “I”,”a”, and the empty string.
Source code:
with open("words.txt", "a") as f:

f.write("\nI\na\n")
f.write("\n")
[*file operation kind of program*]
Output:

2.(iii). Write a python code to read dictionary values from the user. Construct a function to
invert its content. i.e., keys should be values and values should be keys.
def invert_dict(d):
inverted = {}
for key in d:

value = d[key]
if value not in inverted:
inverted[value] = [key]
else:

inverted[value].append(key)

return inverted

d = {}

n = int(input("Enter the number of key-value pairs in the dictionary: "))


for i in range(n):
key = input("Enter the key: ")
value = input("Enter the value: ")
d[key] = value

print("Original dictionary: ")


print(d)
inverted = invert_dict(d)
print("Inverted dictionary: ")
print(inverted)

3. i) Add a comma between the characters. If the given word is ‘Apple’, it should
become ‘A,p,p,l,e’

Source code:
word = input("Enter a word: ")
comma_word = ",".join(word)
print(comma_word)
Output:
Enter a word:APPLE
A,P,P,L,E

ii) Remove the given word in all the places of a string

Source code:
def remove_word(string, word):
new_string = string.replace(word, "")
return new_string
string = input("Enter a string: ")
word = input("Enter a word to remove: ")
new_string = remove_word(string, word)
print("New string:", new_string)
Output:
Enter a string:avniet aiml
avnietaiml

iii) Write a function that takes a sentence as an input parameter and replaces the
first letter of every word with corresponding upper case letter and the rest of the
letters in the word by corresponding letters in lower case without using an in-built
function?

Source code:
def capitalize_words(sentence):
words = sentence.split()
new_sentence = ""
for word in words:
new_word = word[0].upper() + word[1:].lower()
new_sentence += new_word + " "
return new_sentence.strip()
sentence= input("Enter a sentence: ")
new_sentence = capitalize_words(sentence)
print(new_sentence)
Output:
sentence = "hello cSE and aI&ML STUDENTS, how are you."
print(capitalize_first_letter(sentence))
OUT PUT: Hello Cse And Ai&ml Students, How Are You.

4. Write a recursive function that generates all binary strings of n-bit length.

Source code:
def generate_binary_strings(n):
if n == 0:
return ['']
else:
strings = generate_binary_strings(n - 1)
return [s + '0' for s in strings] + [s + '1' for s in strings]
strings = generate_binary_strings(3)
print(strings)
Output:
00
01
10
11

Week-9&10:
1. i) Write a python program that defines a matrix and prints

Source code:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(row)
Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

ii) Write a python program to perform addition of two square matrices.

Source code:
#defining the matrices
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
#declaring the resultant matrix
result_matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
#modifying the resultant matrix to the sum
for i in range(3):
for j in range(3):
result_matrix[i][j] = matrix1[i][j] + matrix2[i][j]
#printing the resultant matrix
for row in result_matrix:
print(row)
Output:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

iii) Write a python program to perform multiplication of two square matrices.

Source code:
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

result_matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]


for i in range(3):
for j in range(3):
for k in range(3):
result_matrix[i][j] += matrix1[i][k] * matrix2[k][j]

for row in result_matrix:


print(row)
Output:
[30, 20, 10]
[60, 40, 20]
[90, 60, 30]

2. how do you make a module?Give an example of construction of a module using


different geometricalshapes and operations on them as its functions in python?
Open a new Python file and save it with a name, for example, "geometry.py".
Define functions that implement different operations on geometrical shapes. For
example, you can define functions for calculating the area and perimeter of a circle,
rectangle, and triangle. Here's an example code for the functions:
Source code:
import math

def circle_area(radius):
return math.pi * radius ** 2

def circle_perimeter(radius):
return 2 * math.pi * radius

def rectangle_area(length, width):


return length * width

def rectangle_perimeter(length, width):


return 2 * (length + width)

def triangle_area(base, height):


return 0.5 * base * height

def triangle_perimeter(side1, side2, side3):


return side1 + side2 + side3
Save the file.
Import the module in another Python file and use its functions. Here's an example code:
import geometry

print(geometry.circle_area(5))
print(geometry.rectangle_perimeter(4, 6))
print(geometry.triangle_area(3, 4))

Output:

78.53981633974483
20
6.0
3. Use the Structure of Exception hadling all general purpose exceptions using
python

Source code:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("The result is:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
except Exception as e:
print("An error occurred:", e)
Output:
Enter a number:10
Enter another number:5
The result is:2

WEEK-11&12:
1. (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 using python
import turtle

def draw_rectangle(canvas, rectangle):


# Create a turtle object and set its speed to 0 (fastest)
turtle_obj = turtle.Turtle()
turtle_obj.speed(0)

# Set the turtle's position to the top-left corner of the rectangle


turtle_obj.penup()
turtle_obj.goto(rectangle[0][0], rectangle[0][1])

# Draw the rectangle


turtle_obj.pendown()
turtle_obj.goto(rectangle[1][0], rectangle[0][1])
turtle_obj.goto(rectangle[1][0], rectangle[1][1])
turtle_obj.goto(rectangle[0][0], rectangle[1][1])
turtle_obj.goto(rectangle[0][0], rectangle[0][1])

# Hide the turtle and update the canvas


turtle_obj.hideturtle()
canvas.update()
# Create the canvas
canvas = turtle.Screen()

# Define the rectangle


rectangle = ((-100, 100), (100, -100))
# Draw the rectangle
draw_rectangle(canvas, rectangle)

# Keep the window open


canvas.mainloop()
Output:

1.(b) add an a attribute named color to your rectangle objects and modify draw
rectangle so that it uses the color attribute as athe fill color
import turtle

# creating turtle pen


t = turtle.Turtle()

# taking input for the side of the rectangle


l = int(input("Enter the length of the Rectangle: "))
w = int(input("Enter the width of the Rectangle: "))

col = input("Enter the color name or hex value of color(# RRGGBB): ")

# set the fillcolor


t.fillcolor(col)

# start the filling color


t.begin_fill()

# drawing first side


t.forward(l) # Forward turtle by l units
t.left(90) # Turn turtle by 90 degree

# drawing second side


t.forward(w) # Forward turtle by w units
t.left(90) # Turn turtle by 90 degree

# drawing third side


t.forward(l) # Forward turtle by l units
t.left(90) # Turn turtle by 90 degree

# drawing fourth side


t.forward(w) # Forward turtle by w units
t.left(90) # Turn turtle by 90 degree
# taking the input for the color

# ending the filling of the color


t.end_fill()

Output:
1.(c) Write a function called draw point that takes a canvas and a point as arguments and
draw a representation of the point on the canvas
import tkinter as tk

def draw_point(canvas, point):


x, y = point
canvas.create_oval(x-2, y-2, x+2, y+2, fill='black')
# create a tkinter window and canvas
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

# define a point
point = (200, 200)

# draw the point on the canvas


draw_point(canvas, point)

# start the tkinter event loop


root.mainloop()

Output:

1.(d) Define a new class called circle with appropriate attributes and instantiate a few circle
objects . Write a function called draw circles that draw circles on the canvas
Source code:
import turtle

class Circle:

def init (self, x, y, radius):


self.x = x
self.y = y
self.radius = radius
def str (self):
return f"Circle at ({self.x}, {self.y}) with radius {self.radius}"
def draw_circles(circles):
t = turtle.Turtle()
t.speed('fastest')
t.penup()
for circle in circles:

t.goto(circle.x, circle.y)
t.pendown()

t.circle(circle.radius)
t.penup()

turtle.done()
# Create some Circle objects
c1 = Circle(0, 0, 50)
c2 = Circle(-100, 100, 75)

c3 = Circle(100, -100, 25)

# Draw the circles on a canvas


draw_circles([c1, c2, c3])

Output:
2.Write a Python program to demonstrate the usage of method resolution order (MRO) in
multiple levels of inheritance
Source code:
class A:

def method(self):
print("A's method called")

class B(A):

def method(self):
print("B's method called")
super().method()

class C(A):

def method(self):
print("C's method called")
super().method()

class D(B, C):


def method(self):

print("D's method called")

super().method()

d = D()
d.method()
Python follows a depth-first lookup order and hence ends up calling the method from class A.
By following the method resolution order, the lookup order as follows.
Class D -> Class B -> Class C -> Class A

3.Write a Python code to read phone number and email id from the user and validate it
for correctness

Source code:
import re

# read phone number from user


phone_number = input("Enter your phone number: ")

# validate phone number using regex


if re.match(r'^\d{10}$', phone_number):
print("Phone number is valid.")
else:
print("Phone number is invalid.")

# read email ID from user


email_id = input("Enter your email ID: ")

# validate email ID using regex


if re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email_id):print("Email
ID is valid.")
else:
print("Email ID is invalid.")
Output:
Enter your phone number:9948689899
The phone number is valid
Enter your email ID:aiml@gmail
Email id is invalid.

WEEK-13&14:

1. Write a program to merge two given files contents into the third file

Source code:

# open first file for reading


with open('file1.txt', 'r') as f1:
contents1 = f1.read()

# open second file for reading


with open('file2.txt', 'r') as f2:
contents2 = f2.read()

# concatenate the contents of both files


merged_contents = contents1 + contents2
# open third file for writing and write merged contents to it
with open('file3.txt', 'w') as f3:
f3.write(merged_contents)
print("Merged contents written to file3.txt")
Output:
i am in file one
i am in file two
i am in file one
i am in file two
i am in file one
i am in file two

2. Write a python code to open a given file and construct a function to check for given
words present in it and display on found

Source code:

def check_words_in_file(file_path, words_to_check):


# Open the file and read its contents
with open(file_path, 'r') as f:
file_contents = f.read()

# Check for the presence of each word in the file


for word in words_to_check:
if word in file_contents:
print(f"{word} was found in the file at least once.")
else:
print(f"{word} was not found in the file.")

# Example usage
file_path = 'example.txt'
words_to_check = ['hello', 'world', 'Python']
check_words_in_file(file_path, words_to_check)
Output:
ENTER THE WORD TO SEARCH===world
word found

3. Write a python code read text from the text file, find the word with most number of
occurrences from collections import Counter

Source code:
# Open the file and read its contents
with open('filename.txt', 'r') as file:
contents = file.read()

# Convert contents to lowercase and split into words


words = contents.lower().split()

# Use the Counter class to count the occurrences of each word


word_counts = Counter(words)

# Find the word with the highest count


most_common_word, count = word_counts.most_common(1)[0]

print(f"The most common word is '{most_common_word}' with {count} occurrences.")


Output:
Planets are made of dust and huge minerals.
Our earth is a habitable planet belongs to milkyway galaxy and it is golden planet.
ENTER THE WORD TO FIND NUMBER OF TIMES REPEATED===and
NUMBER OF WORDS REPATED BY WORD and is == 2

4. write a function that reads a file file1 and display the number of words, number of
vowels, blank spaces, lower case and upper case letters

Source code:

def analyze_file(file_name):
with open(file_name, 'r') as f:
text = f.read()
num_words = len(text.split())
num_vowels = sum(1 for char in text if char.lower() in 'aeiou')
num_spaces = sum(1 for char in text if char == ' ')
num_lower = sum(1 for char in text if char.islower())
num_upper = sum(1 for char in text if char.isupper())

print(f"Number of words: {num_words}")


print(f"Number of vowels: {num_vowels}")
print(f"Number of spaces: {num_spaces}")
print(f"Number of lower case letters: {num_lower}")
print(f"Number of upper case letters: {num_upper}")
analyze_file('file1.txt')
Output:
Planets are made of dust and huge minerals
Planets are made of dust and huge minerals
['Planets', 'are', 'made', 'of', 'dust', 'and', 'huge', 'minerals']
TOTAL NUMBER OF WORDS IS===== 8
TOTAL NUMBER OF UPPER IS===== 1
TOTAL NUMBER OF LOWER IS===== 34
TOTAL NUMBER OF OVAL IS===== 14
TOTAL NUMBER OF CONSONANTS IS===== 21
WEEK-15&16:

1. Import numpy, plotly, and scipy and explore their functionalities.


Numpy:
NumPy (Numerical Python) is a Python library that provides support for large, multi-
dimensional arrays and matrices, as well as a wide range of mathematical functions to
operate on these arrays. It is one of the fundamental libraries in Python's scientific
computing ecosystem, alongside libraries like Pandas, SciPy, and Matplotlib.

Some key features and functionalities in Numpy include:


1. Arrays
2. Broadcasting
3. Mathematical functions
4. Linear Algebra
5. Random number generation
6. integration with another libraries

Plotly:
Plotly is a Python library that provides a variety of graphing tools, such as scatter
plots, line plots, bar charts, histograms, heatmaps, and more. Plotly provides a user-
friendly interface for creating interactive plots and visualizations that can be easily
shared online or embedded into web pages.

Some key features of Plotly are:


1. Interactive plots
2. Exploring
3. Collaboration
4. Dashboard creation
5. Integration with other libraries

SciPy :
SciPy (Scientific Python) is a Python library for scientific computing and
technical computing. It provides a wide range of scientific algorithms and
functions that can be used for tasks such as optimization, integration,
interpolation, signal processing, linear algebra, and more. SciPy builds on top of
the NumPy library, which provides support for large, multi-dimensional arrays
and matrices.

Some key features of SciPy are:


1. Optimization.
2. Integration.
3. Interpolation .
4. Signal processing.
5. Linear algebra.
6. Statistical functions.
7. Integration with other libraries.

2. Write a program to implement digital logic gates- AND, OR, NOT, EX-OR

Source code:
def AND_gate(x1, x2):
Implements the AND logic gate.

Inputs:
x1 (int): The first input to the AND gate (either 0 or 1).
x2 (int): The second input to the AND gate (either 0 or 1).

Returns:
int: The output of the AND gate (either 0 or 1).
if x1 == 1 and x2 == 1:
return 1
else:
return 0

def OR_gate(x1, x2):


Implements the OR logic gate.

Inputs:
x1 (int): The first input to the OR gate (either 0 or 1).
x2 (int): The second input to the OR gate (either 0 or 1).

Returns:
int: The output of the OR gate (either 0 or 1).
if x1 == 1 or x2 == 1:
return 1
else:
return 0

def NOT_gate(x):

Implements the NOT logic gate.

Inputs:
x (int): The input to the NOT gate (either 0 or 1).

Returns:
int: The output of the NOT gate (either 0 or 1).

if x == 1:
return 0
else:
return 1

def XOR_gate(x1, x2):

Implements the XOR logic gate.


Inputs:
x1 (int): The first input to the XOR gate (either 0 or 1).
x2 (int): The second input to the XOR gate (either 0 or 1).

Returns:
int: The output of the XOR gate (either 0 or 1).
if x1 == x2:
return 0
else:
return 1

# Testing the logic gates


print("AND gate")
print(AND_gate(0, 0)) # Output: 0
print(AND_gate(0, 1)) # Output: 0
print(AND_gate(1, 0)) # Output: 0
print(AND_gate(1, 1)) # Output: 1

print("OR gate")
print(OR_gate(0, 0)) # Output: 0
print(OR_gate(0, 1)) # Output: 1
print(OR_gate(1, 0)) # Output: 1
print(OR_gate(1, 1)) # Output: 1

print("NOT gate")
print(NOT_gate(0)) # Output: 1
print(NOT_gate(1)) # Output: 0

print("XOR gate")
print(XOR_gate(0, 0)) # Output: 0
print(XOR_gate(0, 1)) # Output: 1
print(XOR_gate(1, 0)) # Output: 1
print(XOR_gate(1, 1)) # Output: 0
Output:
| AND Truth Table | Result |
A = False, B = False | A AND B = False |
A = False, B = True | A AND B = False |
A = True, B = False | A AND B = False |
A = True, B = True | A AND B = True |

3. Write a program to implement Half Adder, Full Adder and Parallel Adder.

Source code:
# Half Adder
def half_adder(a, b):
sum = a ^ b # XOR
carry = a & b # AND
return sum, carry
# Full Adder
def full_adder(a, b, carry_in):
s1, c1 = half_adder(a, b)
s2, c2 = half_adder(s1, carry_in)
sum = s2
carry_out = c1 | c2
return sum, carry_out

# Parallel Adder
def parallel_adder(a, b):
assert len(a) == len(b), "Lengths of input arrays do not match"
n = len(a)
carry = 0
result = [0] * n
for i in range(n-1, -1, -1):
sum, carry = full_adder(a[i], b[i], carry)
result[i] = sum
if carry == 1:
result.insert(0, carry)
return result

# Testing the adders


a = [1, 0, 1, 1] # Binary number 1011
b = [1, 1, 0, 0] # Binary number 1100
# Half Adder
sum, carry = half_adder(a[0], b[0])
print("Half Adder")
print("Sum: ", sum) # Output: 0
print("Carry: ", carry) # Output: 1

# Full Adder
sum, carry = full_adder(a[0], b[0], 0)
print("Full Adder")
print("Sum: ", sum) # Output: 0
print("Carry: ", carry) # Output: 1

# Parallel Adder
result = parallel_adder(a, b)
print("Parallel Adder")
print("Result: ", result) # Output: [1, 0, 0, 1, 1]
Output:
Half adder:
Sum 0
Carry 1
Full adder:
Sum 0
Carry 1
Parallel Adder:
Result: [1, 0, 0, 1, 1]
4. Write a GUI program to create a window wizard having two text labels, two text
fields and two buttons as submit and reset.
Source code:

import tkinter as tk

class WindowWizard:
def init (self, master):
self.master = master
master.title("Window Wizard")

# Create and place labels


self.label1 = tk.Label(master, text="Enter your name:")
self.label1.grid(row=0, column=0, padx=10, pady=10)
self.label2 = tk.Label(master, text="Enter your email:")
self.label2.grid(row=1, column=0, padx=10, pady=10)

# Create and place text fields


self.entry1 = tk.Entry(master)
self.entry1.grid(row=0, column=1, padx=10, pady=10)
self.entry2 = tk.Entry(master)
self.entry2.grid(row=1, column=1, padx=10, pady=10)

# Create and place buttons


self.submit_button = tk.Button(master, text="Submit", command=self.submit)
self.submit_button.grid(row=2, column=0, padx=10, pady=10)
self.reset_button = tk.Button(master, text="Reset", command=self.reset)
self.reset_button.grid(row=2, column=1, padx=10, pady=10)

def submit(self):
# Get the input values
name = self.entry1.get()
email = self.entry2.get()

# Do something with the input values (e.g., print them to console)


print("Name:", name)
print("Email:", email)

def reset(self):
# Clear the input fields
self.entry1.delete(0, tk.END)
self.entry2.delete(0, tk.END)

root = tk.Tk()
window = WindowWizard(root)
root.mainloop()
Output:

You might also like