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

Python Programming Lab Manual

The document is a Python Programming Lab Manual for B.Tech I Year II Semester students, outlining course objectives, outcomes, and a detailed weekly schedule of lab experiments. It covers fundamental Python concepts such as control structures, data types, file handling, and GUI programming, along with practical coding exercises. Additionally, it provides an introduction to Python, its features, applications, and recommended textbooks and references.

Uploaded by

shahid9346394038
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Programming Lab Manual

The document is a Python Programming Lab Manual for B.Tech I Year II Semester students, outlining course objectives, outcomes, and a detailed weekly schedule of lab experiments. It covers fundamental Python concepts such as control structures, data types, file handling, and GUI programming, along with practical coding exercises. Additionally, it provides an introduction to Python, its features, applications, and recommended textbooks and references.

Uploaded by

shahid9346394038
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

PYTHON PROGRAMMING LAB MANNUAL

B.TECH I YEAR II SEMESTER-R22 REGULATION


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:
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 - 2:
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
uppercase 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 - 3:
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 - 4:
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 - 5:
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
geometricalshapes and operations on them as its functions.
3. Use the structure of exception handling all general purpose exceptions.

Week-6:
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
a representation 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
multiple levels of Inheritances.
3. Write a python code to read a phone number and email-id from the user and validate it
for correctness.

Week- 7
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 in it 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 - 8:
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
buttons as 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
INTRODUCTION TO PYTHON PROGRAMMING

 Python is a high-level, general-purpose, interpreted, interactive and object-oriented


programming language.
 It was created by Guido van Rossum during 1985- 1990.
 Like Perl, Python source code is also available under the GNU General Public License
(GPL).

Why the name python?


Guido van Rossum was interested on watching a comedy show, which is telecasting on the BBC
channelfrom 1969 to 1974 The complete Monty Python's Flying Circus.
Guido Van Rossum thought he needed a name that was short, unique, and slightly
mysterious for his programming language, so he decided to call the language Python.

FEATURES OF PYTHON
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python
is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages.
Python's features include the following –
• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and cross platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same
interface on allplatforms.
• Extendable − We can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and ported to
many systemcalls, libraries and windows systems, such as Windows MFC, Macintosh, and the
X Window system ofUnix.
• Scalable − Python provides a better structure and support for large programs than shell scripting.

APPLICATIONS OF PYTHON PROGRAMMING


 Web Development
 Game Development
 Scientific and Numeric applications
 Artificial Intelligence and Machine Learning based applications
 Data Science related applications
 Desktop GUI applications
 Software Development
 Enterprise-level/Business Applications
 Education programs and training courses
 Web Scraping Applications
 Image Processing and Graphic Design Applications
 Data Analysis
WEEK-1
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.

import webbrowser
open('http://www.python.org')

1. (ii) Start the Python interpreter and type help() to start the
online 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 comes with
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")
3. (i) Write a program to calculate compound interest when principal, rate and
numbers o f p e r i o d s a r e 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)

3. (ii)Given coordinates (x1, y1), (x2, y2) find the distance between two
points.
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)
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)

WEEK-2
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)

2. Write a program to check whether the given input is digit or lowercase character
or 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")

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

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)
WEEK-3
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)
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)))

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))

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")

Week-4
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

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]))

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.

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)

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.
with open("words.txt", "a") as f:
f.write("\nI\na\n")
f.write("\n")

[*file operation kind of program*]

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’

word = input("Enter a word: ")


comma_word = ",".join(word)
print(comma_word)

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

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)

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?

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)

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

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)

Week-5
1. i) Write a python program that defines a matrix and prints

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


for row in matrix:
print(row)

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

#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)

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

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)

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:
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))
3. Use the Structure of Exception hadling all general purpose exceptions using
python

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)

WEEK-6
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()

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()
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()

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
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])

2.Write a Python program to demonstrate the usage of method resolution order (MRO) in
multiple levels of inheritance
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

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.")

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

# 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")

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

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)

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

# 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.")

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

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')

WEEK-8

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

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

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

# 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]

4. 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 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()

You might also like