0% found this document useful (0 votes)
22 views50 pages

I-II PPL Lab Manual Format-R22 Aids

The document is a lab manual for the Python Programming Lab course for B.Tech students in the Department of AI&DS for the academic year 2024-2025. It outlines the vision and mission of the department, program outcomes, course objectives, and detailed instructions for lab sessions, including evaluation criteria and a list of practical exercises. Students will learn to develop programs using Python and C, focusing on algorithms, data structures, and file handling.
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)
22 views50 pages

I-II PPL Lab Manual Format-R22 Aids

The document is a lab manual for the Python Programming Lab course for B.Tech students in the Department of AI&DS for the academic year 2024-2025. It outlines the vision and mission of the department, program outcomes, course objectives, and detailed instructions for lab sessions, including evaluation criteria and a list of practical exercises. Students will learn to develop programs using Python and C, focusing on algorithms, data structures, and file handling.
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/ 50

PYTHON PROGRAMMING LAB

LAB MANUAL (R22)


B.Tech I Year – II Semester
ACADEMIC YEAR (2024-2025)
Department of AI&DS

1|Page
VISION
To empower female students with professional education using creative & innovative technical practices of
global competence and research aptitude to become competitive engineers with ethical values and
entrepreneurial skills.

MISSION
 To impart value based professional education through creative and innovative teaching-learning process
to face the global challenges of the new era technology.

 To inculcate research aptitude and to bring out creativity in students by imparting engineering
knowledge imbibing interpersonal skills to promote innovation, research and entrepreneurship.

DEPARTMENT OF AIDS

Department Vision:
To be a leading department of Artificial Intelligence and Data Science that provides cutting-edge education, research, and
innovation in the field, and prepares graduates to become globally competitive professionals, researchers, and
entrepreneurs.

Department Mission:

DM1: Providing comprehensive education and training in the principles, tools, and applications of Artificial Intelligence
and Data Science, to prepare graduates for a wide range of careers and research opportunities.

DM2: Conducting cutting-edge research in the field of Artificial Intelligence and Data Science, including the
development of new algorithms, models, and platforms for data analysis, machine learning, and deep learning.

DM3: Fostering collaborations and partnerships with industry, government, and academia to promote the transfer of
technology, innovation, and entrepreneurship.

Program Outcomes:
1 PO1:Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
2 PO2:Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences
3 PO3:Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
4 PO4:Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
5 PO5:Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6 PO6:The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7 PO7:Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8 PO8:Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
9 PO9:Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10 PO10:Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and give and receive clear instructions.
11 PO11:Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multidisciplinary environments
12 PO12:Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Program Specific Outcome:

1 PSO1: Professional skills : the ability to understand ,analyze and develop computer programs in the
areas related to algorithms, system software

2 PSO2:Problem solving skills:the ability to apply standard practices and strategies in software project
development to deliver a quality and defect free product.
3 PSO3:Successful career and Entrepreneurship: the ability to employ modern computer languages,
techniques, in creating innovative career paths to be an entrepreneur and a zest for higher studies

PROGRAM EDUCATIONAL OBJECTIVES


PEO No. Program Educational Objectives

To apply engineering processes and practices to software and hardware systems


PEO1
skillfully and efficiently.

Ability to understand and analyze engineering issues in a broader prospective with


PEO2
ethical responsibility.

To prepare students to fit into any industry associated with developing and
PEO3
implementation of software products or technologies.

PEO4 To equip the graduates with ability to analyze, design and test the novel products.
Course Structure

Course Title PYTHON PROGRAMMING LAB


Course Code
Programme B.Tech
Course Structure Practical
L T P Credits
0 0 3 1.5

Course Objectives:
The students will learn the following:
To work with an IDE to create, edit, compile, run and debug programs
To analyze the various steps in program development.
To develop programs to solve basic problems by understanding basic concepts in C
like operators, control statements etc.
To develop modular, reusable and readable C Programs using the concepts like
functions,
arrays etc.
To write programs using the Dynamic Memory Allocation concept.
To create, read from and write to text and binary files

Course Outcomes

The student is expected to learn from this laboratory course the concept of error and its analysis
It also allows the student to develop experimental skills to design new experiments in
Engineering. With the exposure to these experiments the student can compare with the correlate
with experiment.
CO1. Demonstrate the basic purpose of computer applications in various domains.
CO2. Write, compile, and debug the programs in C Language.

CO3. Design the programs involving basic operations, decision structures and looping
structures.

CO4. Explain the need of writing programs using functions and parameter passing
techniques.
CO5. Demonstrate the array concepts, structure concepts and dynamic memory allocation
with the help of pointers.

CO6. Use different types of files for reading and writing the data into persistent storage
device and explain the role of simple data structures like stacks, queues

PYTHON PROGRAMMING LAB

PPL – Credits :1.5


AIDS,IT

Instructions : 3 practicals hrs/week Sessional Marks :40

End Exam : 3 hours End Exam:60

OBJECTIVES:

The course should enable the students to:


Formulate problems and implement algorithms using C programming language.
Develop programs using decision structures, loops and functions.
Learn memory allocation techniques using pointers.
Use structured programming approach for solving of computing problems in real world.

At the end of this course students will demonstrate the ability to


S.NO DESCRIPTION

1 State to describe the algorithms for problems to be solved.

2 Translate the algorithms/flowcharts into C programs using arrays and functions

3 Develop the programs on files and preprocessor directives.

4 Analyze problems using functions and make use of DMA functions.

5. Evaluate the problems to implement searching and sorting techniques.


SCHEME OF EVALUATION
Total Marks For Each Student to Evaluate In Lab: 100 Marks

Internal Examination
Internal Examination External Exam Marks-
S.NO (Continuous Internal
(Continuous Internal Evaluation 60 M
Evaluation): 40 M

1 A Write Up On Day-To-Day 10 Write-Up – 10

2 Experiment In The Laboratory 10 Experiment/Program-15

3 Internal Examination 10 Evaluation of Results-15

4 Activity 10 Presentation on another


INSTRUCTIONS FOR STUDENT WHILE ENTERING IN LAB

These are the instructions for the students attending the lab:

Before entering the lab the student should carry the following things
(MANDATORY)
1. Identity card issued by the college.
2. Class notes
3. Lab observation book
4. Lab Manual
5. Lab Record
Student must sign in and sign out in the register
provided when attending the lab session without fail.
Come to the laboratory in time. Students, who are late
more than 15 min., will not be allowed to attend the
lab.
Students need to maintain 100% attendance in lab if not a strict
action will be taken. All students must follow a Dress Code
while in the laboratory
Foods, drinks are NOT allowed.
All bags must be left at the indicated place.

Refer to the lab staff if you need any


help in using the lab. Respect the
laboratory and its other users.
Workspace must be kept clean and tidy after experiment is completed.
Read the Manual carefully before coming to the laboratory and
be sure about what you are supposed to do.
Do the experiments as per the instructions given in the manual.
Copy all the programs to observation which are
taught in class beforeattending the lab session.
Students are not permitted to use phones, Flash
drives, Internet without permission of lab-in charge.

Lab records need to be submitted on or before the date of submission.

8
List of programs:
PYTHON PROGRAMMING LABORATORY
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 websitehttp://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
33 3
22 2 2
1 1111
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.
9
3. Write a function called palindrome that takes a string argument and returnsTrue 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
geometrical shapes 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.
10 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.

11
INTRODUCTION TO COMPUTERS

What are Computer Programming Languages?


Computer programming languages allow us to give instructions to a computer in a language the
computer understands. Just as many human-based languages exist, there are an array of computer
programming languages that programmers can use to communicate with a computer. The portion
of the language that a computer can understand is called a “binary.” Translating programming
language into binary is known as “compiling.” Each language, from C Language to Python, has
its own distinct features, though many times there are commonalities between programming
languages.

PYTHON PROGRAMMING LAB MANUAL


1. Aim: Write a program to calculate compound interest when principal, rate
and number of periods are given.

Program:

def compound_interest(principal, rate, time):

# Calculates compound interest

Amount = principal * (pow((1 + rate / 100), time))

CI = Amount - principal

print("Compound interest is", CI)

# Driver Code

#Taking input from user.

principal = int(input("Enter the principal amount: "))

rate = int(input("Enter rate of interest: "))

time = int(input("Enter time in years: " ))

20
#Function Call

compound_interest(principal,rate,time)

Input:
Enter the principal amount: 3000
Enter rate of interest: 5
Enter time in years: 3
Output:
Compound interest is 472.875

1
2. Aim: Given coordinates (x1, y1), (x2, y2) find the distance between
two points.
Program:
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)

Output :
enter x1 : 4

enter x2 : 6

enter y1 : 0

enter y2 : 6

distance between (4, 6) and (0, 6) is : 6.324555320336759

2
3. Aim: Read name, address, email and phone number of a person through
keyboard and print the details.

Program:

def personal_details():
name, age = "Simon", 19
address = "Bangalore, Karnataka, India"
print("Name: {}\nAge: {}\nAddress: {}".format(name, age, address))

personal_details()

OUTPUT:

Name: Simon
Age: 19
Address: Bangalore, Karnataka, India

3
4. Aim: Print the below triangle using for loop.

Program:

rows = 6
# if you want user to enter a number, uncomment the below line
# rows = int(input('Enter the number of rows'))
# outer loop
for i in range(rows):
# nested loop
for j in range(i):
# display number
print(i, end=' ')
# new line after each row
print('')

OUTPUT:

22

333

4444

5 5555

4
5. Aim: 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).

Program:
ch = input("Please Enter Your Own Character : ")

if(ch >= 'A' and ch <= 'Z'):

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

elif(ch >= 'a' and ch <= 'z'):

print("The Given Character ", ch, "is a Lowercase Alphabet")

else:

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

OUTPUT:

Please Enter Your Own Character : o

The Given Character o is a Lowercase Alphabet

>>>

Please Enter Your Own Character : R

The Given Character R is an Uppercase Alphabet

>>>

Please Enter Your Own Character : $

The Given Character $ is Not a Lower or Uppercase Alphabet

5
6. Aim: Python Program to Print the Fibonacci sequence using while loop.

Program: Number =
int(input("\nPlease Enter the Range : "))#
Initializing First and Second
Values i = 0
First_Value = 0
Second_Value = 1
# Find & Displaying
while(i < Number):
if(i <= 1):
Next = i
else:
Next = First_Value + Second_Value
First_Value = Second_Value
Second_Value = Next
print(Next)
i=i+1

OUTPUT:

Please Enter the Range : 4

6
7. Aim: Python program to print all prime numbers in a given interval (use
break).

Program:

def primenumber(MyNum):
n=0
i=2
for i in range(2,MyNum//2+1):
if MyNum % i == 0:
n=n+1
break
if n == 0:
print(MyNum, end=" ")

x = 50
print("Prime numbers less than", x, "are:")
for i in range(2, x+1):
primenumber(i)
OUTPUT:

Prime numbers less than 50 are:


23571113171923293137414347

7
8. Aim:
i) Write a program to convert a list and tuple into arrays.

Program:
def convert(list):
return tuple(i for i in list)
# Driver function
list = [1, 2, 3, 4]
print(convert(list))

OUTPUT:
(1, 2, 3, 4)

8
Aim:
ii) Write a program to find common values between two arrays.
Program:

array1 = [1, 2, 3, 4, 5]
array2 = [4, 5, 6, 7, 8]

common_values = set(array1) & set(array2)

print("The common values between the two arrays are:", list(common_values))

OUTPUT:
The common values between the two arrays are: [4, 5]

9
9. Aim: Write a function called gcd that takes parameters a and b and returns
their greatest common divisor.
Program:

def GCD_Loop( a, b):


if a > b: # define the if condition
temp = b
else:
temp = a
for i in range(1, temp + 1):
if (( a % i == 0) and (b % i == 0 )):
gcd = i
return gcd
x = int(input (" Enter the first number: ") ) # take first no.
y =int (input (" Enter the second number: ")) # take second no.
num = GCD_Loop(x, y) # call the gcd_fun() to find the result
print("GCD of two number is: ") print(num) # call num

Output:

10
10. Aim: Write a function called palindrome that takes a string argument and
returnsTrue 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.
Program:

#Enter input string


string = input("Enter string : ")

#Declare an empty string variable


revstr = ""

#Iterate string with for loop


for i in string:
revstr = i + revstr
print("Reversed string : ", revstr)

if(string == revstr):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

OUTPUT:

11
11. Aim: 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.

Program:

test_list = [1, 4, 5, 8, 10]

# printing original list


print ("Original list : " + str(test_list))

# using naive method to


# check sorted list
flag = 0
i=1
while i < len(test_list):
if(test_list[i] < test_list[i - 1]):
flag = 1
i += 1

# printing result
if (not flag) :
print ("Yes, List is sorted.")
else :
print ("No, List is not sorted.")

Output :
Original list : [1, 4, 5, 8, 10]
Yes, List is sorted.

12
12. Aim: 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 bunique elements from the original. Hint: they don’t have to
be in the same order.

Program:

def Remove(duplicate):
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list

# Driver Code
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print(Remove(duplicate))

Output:
[2, 4, 10, 20, 5]

13
ii).
Aim: 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.
Program:
def invert_dict(d):
inverse = {}
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse

# Ask user to input


dictionary d = {}
while True:
key = input("Enter key (or 'q' to stop): ")
if key == 'q':
break
val = input("Enter value:
") d[key] = val

# Print original dictionary


print("Original dictionary:")
print(d)

# Invert dictionary using function and print


result print("Inverted dictionary:")
inverse = invert_dict(d)
print(inverse)

OUTPUT:
Enter key (or 'q' to stop): 22
Enter value: "ram"
Enter key (or 'q' to stop): 34
Enter value: "sita"
Enter key (or 'q' to stop): 54
Enter value: "mahesh"
Enter key (or 'q' to stop): q
Original dictionary:
{'22': '"ram"', '34': '"sita"', '54': '"mahesh"'}
Inverted dictionary:
{'"ram"': ['22'], '"sita"': ['34'], '"mahesh"': ['54']}

14
13.
Aim:
i) Add a comma between the characters. If the given word is 'Apple', it should
become 'A,p,p,l,e'
Program:

def add_comma(word):
comma_word = ','.join(word)
return comma_word

# calling function
add_comma("apple")

OUTPUT:

a,p,p,l,e

15
Aim:
ii) Remove the given word in all the places in a string?

Program:

def remove_word(word, text):


"""
Removes all occurrences of a word in a given string.
"""
return text.replace(word, '')

text = "This is a test string. This is only a test."


word = "test"
new_text = remove_word(word, text)
print(new_text)

OUTPUT:
This is a string. This is only a .

16
Aim:
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?

Program:

def title_case(sentence):
# Split the sentence into words
words = sentence.split()

# Iterate over the words and apply the title case


transformation for i in range(len(words)):
word = words[i]
# Extract the first letter and convert it to upper
case first_letter = word[0].upper()
# Extract the rest of the letters and convert them to lower
case rest_letters = word[1:].lower()
# Concatenate the first letter and the rest of the
letters words[i] = first_letter + rest_letters

# Join the words back into a sentence and return it


return ' '.join(words)

# calling a function
sentence = "I am learning python in Malla Reddy College of Engineering for
wo men"
title_case(sentence)

OUTPUT:
I Am Learning Python In Malla Reddy College Of Engineering For Women

17
14.
Aim: Writes a recursive function that generates all binary strings of n-bit
length.

Program:

def printTheArray(arr, n):

for i in range(0, n):


print(arr[i], end = " ")

print()

OUTPUT:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

18
15.
Aim:
i) Write a python program that defines a matrix and prints.

Program:

R = int(input("Enter the number of rows:"))


C = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")

# For user input


for i in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entries
a.append(int(input()))
matrix.append(a)

# For printing the matrix


for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()

Output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries rowwise:
1
2
3
4
5
6

123
456

19
Aim:
ii) Write a python program to perform addition of two square matrices.
Program:

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

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

result = [[X[i][j] + Y[i][j] for j in range


(len(X[0]))] for i in range(len(X))]

for r in result:
print(r)

Output
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

20
Aim:
iii) Write a python program to perform multiplication of two square
matrices.
Program:

# take a 3x3 matrix


A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]

# take a 3x4 matrix


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

result = [[0, 0, 0, 0],


[0, 0, 0, 0],
[0, 0, 0, 0]]

# iterating by row of A
for i in range(len(A)):

# iterating by column by B
for j in range(len(B[0])):

# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]

for r in result:
print(r)
Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

21
16.

Aim: 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.
Program:

import shapes
print(shapes.circle_area(5))
print(shapes.square_perimeter(5)

OUTPUT:
78.53981633974483
20

22
17.
Aim: Use the structure of exception handling all general purpose exceptions.

Program:

a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in array


print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred")

OUTPUT:
Second element = 2
An error occurred

23
18.
Aim: 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.

Program:

1 import tkinter as tk
2
3 master = tk.Tk()
4
5
6 def rectangle(event):
7 w.create_rectangle(event.x, event.y, event.x + 10, event.y + 10, fill="blue")
8
9
10 w = tk.Canvas(master, width=200, height=200)
11 w.pack()
12
13 master.bind("&lt;Button-1&gt;", rectangle)
14
15 master.mainloop()

OUTPUT

24
19 .
Aim: Write a Python program to demonstrate the usage of Method Resolution
Order (MRO) in multiple levels of Inheritances.

Program:

class A:
def rk(self):
print(" In class A")
class B(A):
def rk(self):
print(" In class B")

r = B()
r.rk()

Output:

In class B

25
20.
Aim: Write a Python code to merge two given file contents into a
third file.

Program:
data = data2 = ""

# Reading data from file1


with open('file1.txt') as fp:
data = fp.read()

# Reading data from file2


with open('file2.txt') as fp:
data2 = fp.read()

# Merging 2 files
# To add the data of file2
# from next line
data += "\n"
data += data2

with open ('file3.txt', 'w') as fp:


fp.write(data)

OUTPUT:

26
21.
Aim: 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.

Program:

with open('GFG.txt','r') as file:

# reading each line


for line in file:

# reading each word


for word in line.split():

# displaying the words


print(word)

OUTPUT:

27
22.
Aim: Write a Python code to Read text from a text file, find the word with most
number of occurrences.

Program:

word = "apple"
count = 0
with open("temp.txt", 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
count=count+1
print("Occurrences of the word", word, ":", count)

Output:

Occurrences of the word apple: 2

28
23.
Aim: 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.

Program:

def counting(filename):

# Opening the file in read mode

txt_file = open(filename, "r")

# Initialize three variables to count number of vowels,

# lines and characters respectively

vowel = 0

line = 0

character = 0

# Make a vowels list so that we can

# check whether the character is vowel or

not vowels_list = ['a', 'e', 'i', 'o', 'u',

'A', 'E', 'I', 'O', 'U']

# Iterate over the characters present in

file for alpha in txt_file.read():

49
# Checking if the current character is vowel or

not if alpha in vowels_list:

vowel += 1

# Checking if the current character is

# not vowel or new line character

elif alpha not in vowels_list and alpha != "\n":

character += 1

# Checking if the current character

# is new line character or not

elif alpha == "\n":

line += 1

# Print the desired output on the console.

print("Number of vowels in ", filename, " = ", vowel)

print("New Lines in ", filename, " = ", line)

print("Number of characters in ", filename, " = ", character)

# Calling the function counting which gives the desired

output counting('Myfile.txt')

Output:

Number of vowels in MyFile.txt = 23

50
New Lines in MyFile.txt = 2
Number of characters in MyFile.txt = 54

51
24.
Aim: Import numpy, Plotpy and Scipy and explore their functionalities.

Program:

import numpy as np
import matplotlib.pyplot as plt
import scipy as sp

# Create a one-dimensional
array a = np.array([1, 2, 3, 4, 5])

# Create a two-dimensional array


b = np.array([[1, 2, 3], [4, 5, 6]])

# Perform basic arithmetic operations on arrays


c=a+2
d=b*3

# Use NumPy functions to perform mathematical operations on


arrays e = np.sin(a)
f = np.sum(b)

# Reshape an array
g = np.reshape(b, (3, 2))

# Transpose an array
h = np.transpose(b)

# matplot
# Create a simple line plot
x = np.linspace(0, 10,
100) y = np.sin(x)
plt.plot(x, y)
plt.show()

# Create a scatter plot


x = np.random.randn(100)
y = np.random.randn(100)
plt.scatter(x, y)
plt.show()

# Create a histogram
data = np.random.randn(1000)
plt.hist(data, bins=30)

52
plt.show()

# Scipy

# Perform a linear regression


x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
slope, intercept, r_value, p_value, std_err = sp.stats.linregress(x, y)

# Find the roots of a function


def f(x):
return x**3 - 3*x**2 + 1
root = sp.optimize.root_scalar(f, method='brentq', bracket=[-10, 10])

# Perform Fourier transforms


data = np.random.randn(1000)
fft = sp.fft.fft(data)

53
25.
Aim: Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-
OR

Program:

def AND_gate(a, b):


if a == 1 and b == 1:
return 1
else:
return 0

# OR gate implementation
def OR_gate(a, b):
if a == 1 or b == 1:
return 1
else:
return 0

# NOT gate implementation


def NOT_gate(a):
if a == 0:
return 1
else:
return 0

# XOR gate implementation


def XOR_gate(a, b):
if a != b:
return 1
else:
return 0

54
26.
Aim: Write a program to implement Half Adder, Full Adder, and Parallel Adder

Program:

def half_adder(a, b):


"""
Computes the sum and carry of two bits using a half adder.
"""
sum = a ^ b
carry = a & b
return sum, carry

print(half_adder(9,10))

# Full Adder program

def full_adder(a, b, c):


"""
Computes the sum and carry of three bits using a full adder.
"""
sum = a ^ b ^ c
carry = (a & b) | (b & c) | (c & a)
return sum, carry

print(full_adder(10,5,14))

# Parallel Adder

def parallel_adder(a, b):


"""
Computes the sum of two n-bit binary numbers using a parallel adder.
"""
n = len(a)
carry = 0
result = ""
for i in range(n-1, -1, -1):
sum, carry = full_adder(int(a[i]), int(b[i]), carry)
result = str(sum) + result
if carry:
result = str(carry) + result
return result

# calling function
a = "1010"

55
b = "1101"

print(parallel_adder(a, b)) # Output: 10111

OUTPUT:
(3, 8)
(1, 14)
10111

56
27.
Aim: Write a GUI program to create a window wizard having two text labels,
two text fields and two buttons as Submit and Reset.
Program:

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

# Create two text labels


self.label1 = tk.Label(master, text="Enter your name:")
self.label2 = tk.Label(master, text="Enter your email:")

# Create two text fields


self.entry1 = tk.Entry(master)
self.entry2 = tk.Entry(master)

# Create two buttons


self.submit_button = tk.Button(master, text="Submit", command=self.sub
mit)
self.reset_button = tk.Button(master, text="Reset", command=self.reset)

# Place the widgets on the screen


self.label1.grid(row=0, column=0)
self.entry1.grid(row=0, column=1)
self.label2.grid(row=1, column=0)
self.entry2.grid(row=1, column=1)
self.submit_button.grid(row=2, column=0)
self.reset_button.grid(row=2, column=1)

def submit(self):
name = self.entry1.get()
email = self.entry2.get()
print("Name:", name)
print("Email:", email)

def reset(self):
self.entry1.delete(0, tk.END)
self.entry2.delete(0, tk.END)
if name == ' main ':
root = tk.Tk()
window_wizard = WindowWizard(root)
root.mainloop()

57
58

You might also like