Python Lab Manual-R22
Python Lab Manual-R22
Course Objectives:
1.To install and run the Python interpreter
2.To learn control structures.
3.To Understand Lists and Dictionaries in python.
4.To Handle Strings and Files in Python
Course Outcomes: After completion of this course, student will be able to:
1.Define python syntax, semantics and flow control.
2.Demonstrate proficiency in handling strings, list tuples and arrays.
3 Develop python programs using core data structures.
4 Conduct experiments on file handling, exception handling and modules.
5.Design the application specific codes 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
informationabout 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 aregiven.
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
uppercasecharacter 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)
R22 CMRTC B. Tech CSE(AI&ML)
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 returnsTrue if it is a
palindromeand 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 sortedin ascending order and False otherwise.
2. Write a function called has_duplicates that takes a list and returns True if there is any
element thatappears 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
ii).
want and the empty string.
iii). Write a python code to read dictionary values from the user. Construct a function to
invert itscontent. 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
everyword 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 anddraws a representation of the Rectangle on the Canvas.
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle
so that ituses 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.
R22 CMRTC B. Tech CSE(AI&ML)
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 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, blankspaces, 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 buttonsas Submit and Reset.
TEXT BOOKS:
1. Supercharged Python: Take your code to the next level, Overland 4th Edition, 2019.
2. Mark Lutz, O'reilly ,Learning Python. 5th Edition, 2015.
REFERENCE BOOKS:
1. Vamsi Kurama, Python Programming: A Modern Approach, Pearson, 2017.
2. Sheetal Taneja, Naveen Kumar, Python Programming A Modular Approach with
Graphics, Database, Mobile, and WebApplications, Pearson, 2017.
3. Michael Dawson, Cengage Learning ,Programming with Python, A Book, India
Edition.5th Edition 2013
4. W. Chun ,Core Python Programming, Pearson.2nd Edition ,2006.
5. Kenneth A. Lambert, Introduction to Python, Cengage 2nd Edition, 2017.
Institute Vision:
To Impart quality education in serene atmosphere thus strive for excellence in
Technology and Research.
Institute Mission:
To Create state of art facilities for effective Teaching- Learning Process.
Pursue and Disseminate Knowledge based research to meet the needs of Industry &
Society.
Infuse Professional, Ethical and Societal values among Learning Community.
Department Vision:
To develop competent and socially responsible engineers in the domain of Artificial
Intelligence & Machine Learning for noteworthy contributions to the society.
Department Mission:
To educate the students in fundamental principles of computing and develop the skills
needed to solve practical problems using contemporary computer-based technologies.
To provide State-of-the-art computing laboratory facilities to promote industry-
institute interaction to enhance student’s practical knowledge.
To Inculcate self-learning abilities, team spirit, and professional ethics among the
students to serve society.
Programme Educational Objectives (PEOs):
PEO-1: Graduates will have the ability to adapt, contribute and innovate new systems in the
key domains of Artificial Intelligence and Machine Learning.
PEO-2: Graduates will have the ability to pursue higher education in reputed institutions
with AI Specialization.
PEO-3: Graduates will be ethically and socially responsible solution providers and
entrepreneurs in the field of Computer Science and Engineering with AI&ML Specialization.
Programme Outcomes (POs):
PO1-Engineering Knowledge: Apply the knowledge of Mathematics, Science, Engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2-Problem Analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
Mathematics, Natural Sciences, and Engineering Sciences.
ESTD: 2009
CMR TECHNICAL CAMPUS
UGC AUTONOMOUS
Accredited by NBA & NAAC with ‘A’ Grade
Approved by AICTE, New Delhi and JNTU, Hyderabad
Kandlakoya, Medchal Road, Hyderabad- 501 401, Telangana
The Python interpreter and the extensive standard library are freely available in source or binary form
for all major platforms from the Python web site, https://www.python.org/, and may be freely
distributed.
The same site also contains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.
Python's documentation
The Python documentation pages are available at https://docs.python.org/3.12/. The most helpful sections are
listed here:
The Python language reference at https://docs.python.org/3.12/reference/index.html
ii). Start the Python interpreter and type help ( ) to start the online help utility.
The Python help() function invokes the interactive built-in help system. If the argument is a string, then the
string is treated as the name of a module, function, class, keyword, or documentation topic, and a help page
is printed on the console. If the argument is any other kind of object, a help page on the object is displayed.
To get help, one can enter help mode by typing help() ay python prompt(i.e. >>> prompt) we can see the help
utility appearing as shown in following
Now we can type in the name of a Python object to get helpful information about it:
When we type the name len at the help> prompt and hit Enter , we get help content related to that built-in
function.
We can type ‘topics’ to know about topics in python. Lets enter topics at help prompt.
Among the topics , suppose we want to know about functions, we should enter ‘FUNCTIONS’ in capital letters
since the FUNCTIONS topic is shown in capital letters in help window.
To leave the content and get back to the help> prompt, you can press Q . To leave the help utility, you can
type quit and hit Enter .
We can also use help() with the name of an object as an argument to get information about that object:
Python
>>> help(dir)
dir(...)
dir([object]) -> list of strings
...
Here dir(), we can use this function to inspect the methods and attributes that are available in a particular object:
Python
>>> dir(str)
['__add__', '__class__', ..., 'title', 'translate', 'upper', 'zfill']
>>> dir(tuple)
['__add__', '__class__', ..., 'count', 'index']
When we call dir() with the name of a Python object as an argument, the function attempts to return a list of valid
attributes for that specific object. This is a convenient way to get an idea of what a given object can do.
2. Start Python interpreter and use it as Calculator
3. I) Write a program to calculate compound interest when principal, rate and number of periods are
given
The formula to calculate compound interest annually is given by:
A = P(1 + R/100) t
Compound Interest = A – P
Where,
● A is amount
● P is the principal amount
● R is the rate and
● T is the time span
The formula for distance between two point (x1, y1) and (x2, y2) is √((x2 – x1)² + (y2 – y1)²).
# read name, contact, email and birthday from user and print them
5
44
333
2222
11111
Program-2:
ch=input("Please Enter any Character: \t")
if(ch>='0' and ch<='9'):
print(ch,"is a digit")
elif (ch.isUpper):
print(ch,"is an UpperCase character");
elif (ch.isLower):
print(ch,"is an LowerCase character");
else:
print(ch,"is not an alphabetic character");
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)
Program-1
# Python code to demonstrate naive
# method to compute gcd ( recursion )
def gcd(a, b):
if(b == 0):
return a
else:
return gcd(b, a % b)
# Driver program to test above function
m = int(input("Enter a Number: "))
n = int(input("Enter b Number: "))
print("The gcd of {0} and {1} is : ".format(m,n),end=' ')
print(gcd(m, n))
Program-2
# Recursive function to return gcd of a and b
def gcd(a, b):
# Everything divides 0
if (a == 0):
return b
if (b == 0):
return a
# base case
if (a == b):
return a
# a is greater
if (a > b):
return gcd(a-b, b)
return gcd(a, b-a)
# main function
s = input("Enter a String: ")
#call the function to check the string is palindrome or not
ans =palindrome(s)
print(s," is Palindrome:",end='')
if (ans):
print("TRUE ")
else:
print("FALSE")
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(list):
x=list[:]
x.sort()
if(list==x):
return True
else:
return False
n = int (input ("Enter number of elements in the List: "))
# Declare an empty list
list1 = []
# Iterate for n times take inputs
for i in range (n):
# Take input of ith element as x.
print(i+1,end=' ')
x = int(input(" Element"))
# Append 'x' to the list1.
list1.append(x)
print("Elements are : ",list1)
print(is_sorted(list1))
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.
def has_duplicate(list):
for i in range(len(list)):
for j in range(0, i):
if list[i] == list[j]:
return 'true'
return 'false'
n = int (input ("Enter number of elements: "))
# Declare an empty list
list1 = []
# Iterate for n times take inputs
for i in range (n):
# Take input of Ith element as x.
print(i+1,end=' ')
x = int(input(" Element"))
# Append 'x' to the list1.
list1.append(x)
print("Elements are : ",list1)
print(has_duplicate(list1))
2.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(L):
LS = sorted(L)
res = []
prev = None
for el in LS:
if el != prev:
res.append(el)
prev = el
return res
with open('words.txt','w') as f:
letters=['I','a',""]
# have to add single letter words to the word list;
# also, the empty string is considered a word.
for l in letters:
f.write(l)
f.write('\n')
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
#Creating a dictionary to read values from the user
my_dict={}
print("How many elements ?", end=' ')
n=int(input())
for i in range(n):
print("Enter key:",end=' ')
k=input()
print("Enter its value: ",end=' ')
v=int(input())
my_dict.update({k:v})
print("The dictionary is: ",my_dict)
print()
x = "Apple"
y = ','.join(x)
print(y)
OR
x = "Apple"
y=''
for i in x:
y += i + ','*1
y = y.strip()
print(repr(y))
if status:
text = ' '.join(words)
print('String after deletion:',text)
else:
print('Word not present in string.')
3. 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?
import string
import io
#Method to convert the string
def capitalize_word(s):
#create a stream of the string
s=io.StringIO(s)
result=" "
#Declare a character of space
#To identify that the next character is starting of a new word
for word in s.read().split():
word=word.lower()
word=word.capitalize()
result +=word+" "
#Return the string with trimming
return result.strip()
#Driver Code
if __name__=="__main__":
#Declare the string
s1="cMR technical campus , dept of AIML"
#call the method to capitalize each word
print(capitalize_word(s1))
4. Writes a recursive function that generates all binary strings of n-bit length
# Function to print the output
def printTheArray(arr, n):
print()
if i == n:
printTheArray(arr, n)
return
# Driver Code
if __name__ == "__main__":
n=4
arr = [None] * n
Geometry.py
# a module using different geometrical shapes and operations on them as its functions.
def geometrical_shapes(name):
# function calling
geometrical_shapes(shape_name)
3. Use the structure of exception handling all general purpose exceptions.
# Use the structure of exception handling all general purpose exceptions.
try:
if operation == "*":
else:
match error:
case RuntimeError():
case ValueError():
case ZeroDivisionError():
else:
world = World()
draw_rectangle(a_canvas,box)
world.mainloop()
1. b. Add an attribute named color to your Rectangle objects and modify draw_rectangle
so that ituses the color attribute as the fill color.
world = World()
draw_rectangle(a_canvas,box)
world.mainloop()
1. 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.
world = World()
draw_point(a_canvas,p)
world.mainloop()
1. 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.
class Point(object):
"represents a point in 2-D space"
p = Point()
p.x = 60
p.y = 15
class Circle(object):
"""Represents a circle.
attributes: center point, radius"""
c = Circle()
c.radius = 50
c.center = Point()
c.center.x = 20
c.center.y = 20
def draw_circle(canvas, circle):
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.circle([circle.center.x, circle.center.y], circle.radius)
world = World()
draw_circle(a_canvas,c)
world.mainloop()
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in
multiplelevels of Inheritances.
# 1) Begins with 0 or 91
# 2) Then contains 6,7 or 8 or 9.
# 3) Then contains 9 digits
Pattern = re.compile("(0|91)?[6-9][0-9]{9}")
return Pattern.match(number)
#main method
if __name__ == "__main__":
Merge.py
# Creating a list of filenames
filenames = ['file1.txt', 'file2.txt']
# read the data from file1 and file2 and write it in file3
outfile.write(infile.read())
mergefile = open("file3.txt")
mergefile.close()
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.
Note : create a text file (i.e.. sample.txt) in which we want to count the words in Python
Example:
file1.txt
CMR TECHNICAL CAMPAS
OUR VISION:
To Impart quality education in serene atmosphere thus strive for excellence in Technology and Research.
Search.py
#To Construct a function to Search a word in a file
def search_word(file_path, word):
with open(file_path, 'r') as file:
# read all content of a file
content = file.read()
# check if string present in a file
if word in content:
print('The word {0} exist in a file'.format(word))
else:
print('The word {0} does not exist in a file'.format(word))
Note : create a text file (i.e.. sample.txt) in which we want to count the words in Python
Example:
Sample.txt
Mango banana apple pear
Banana grapes strawberry
Apple pear mango banana
Kiwi apple mango strawberry
Count_word.py
NumPy – Introduction
NumPy is a Python package. It stands for 'Numerical Python'. It is a library con-sisting of
multidimensional array objects and a collection of routines for processing of array.
Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray was also
developed, having some additional functionalities. In 2005, Travis Oliphant created NumPy package by
incorporating the features of Numarray into Numeric package. There are many contributors to this open
source project.
Example 2
# more than one dimensions
import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a)
The output is as follows –
[[1, 2]
[3, 4]]
Example 3
# minimum dimensions
import numpy as np
a = np.array([1, 2, 3,4,5], ndmin = 2)
print a
The output is as follows −
[[1, 2, 3, 4, 5]]
Example 4
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print a
The output is as follows −
[ 1.+0.j, 2.+0.j, 3.+0.j]
SciPy - Introduction
SciPy, a scientific library for Python is an open source, BSD-licensed library for mathematics, science
and engineering. The SciPy library depends on NumPy, which provides convenient and fast N-
dimensional array manipulation. The main reason for building the SciPy library is that, it should work
with NumPy arrays. It provides many user-friendly and efficient numerical practices such as routines for
numerical integration and optimization. This is an introductory tutorial, which covers the fundamentals
of SciPy and describes how to deal with its various modules.
Example 1
pip install plotly "notebook>=5.3" "ipywidgets>=7.2"
Inside Jupyter notebook:
import plotly.graph_objs as go
fig = go.FigureWidget()
# Display an empty figure
fig
# Add a scatter chart
fig.add_scatter(y=[2, 1, 4, 3])
# Add a bar chart
fig.add_bar(y=[1, 4, 3, 2])
# Add a title
fig.layout.title = 'Hello FigureWidget'
See the Python documentation for more examples.
Plotpy - Introduction
plotly.py is an interactive, open-source, and browser-based graphing library for Python :sparkles:
Built on top of plotly.js, plotly.py is a high-level, declarative charting library. plotly.js ships with over 30
chart types, including scientific charts, 3D graphs, statistical charts, SVG maps, financial charts, and
more.
plotly.py is MIT Licensed. Plotly graphs can be viewed in Jupyter notebooks, standalone HTML files, or
hosted online on plot.ly.
Introduction
To run the NumPy program, first, Numpy needs to be installed. Numpy is installed from Python's
official website using pip and conda by running different commands on different operating systems.
Many important packages are automatically installed within the Numpy library.
Logic gates are elementary building blocks for any digital circuits. It takes one or two inputs and
produces output based on those inputs. Outputs may be high (1) or low (0). Logic gates are used for
circuits that perform calculations, data storage, or show off object-oriented programming especially the
power of inheritance.
Types of Logic Gates in Python
There are seven basic logic gates in Python. These are the following:
AND Gate
OR Gate
NOT Gate
NAND Gate
NOR Gate
XOR Gate
print("+---------------+----------------+")
print(" | AND Truth Table | Result |")
print(" A = False, B = False | A AND B =",AND(False,False)," | ")
print(" A = False, B = True | A AND B =",AND(False,True)," | ")
print(" A = True, B = False | A AND B =",AND(True,False)," | ")
print(" A = True, B = True | A AND B =",AND(True,True)," | ")
2. OR Gate in Python
The OR gate gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.
# working of OR gate
def OR(a, b):
if a == 1 or b ==1:
return True
else:
return False
# Driver code
if __name__=='__main__':
print(OR(0, 0))
print("+---------------+----------------+")
print(" | OR Truth Table | Result |")
print(" A = False, B = False | A OR B =",OR(False,False)," | ")
print(" A = False, B = True | A OR B =",OR(False,True)," | ")
print(" A = True, B = False | A OR B =",OR(True,False)," | ")
print(" A = True, B = True | A OR B =",OR(True,True)," | ")
def NOT(a):
return not a
# Driver code
if __name__=='__main__':
print(NOT(0))
print("+---------------+----------------+")
print(" | NOT Truth Table | Result |")
print(" A = False | A NOT =",NOT(False)," | ")
print(" A = True, | A NOT =",NOT(True)," | ")
4. XOR Gate in Python
The XOR gate gives an output of 1 if either of the inputs is different, it gives 0 if they are the same.
# working of Xor gate
# Driver code
if __name__=='__main__':
print(XOR(5, 5))
print("+---------------+----------------+")
print(" | XOR Truth Table | Result |")
print(" A = False, B = False | A XOR B =",XOR(False,False)," | ")
print(" A = False, B = True | A XOR B =",XOR(False,True)," | ")
print(" A = True, B = False | A XOR B =",XOR(True,False)," | ")
print(" A = True, B = True | A XOR B =",XOR(True,True)," | ")
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
Half Adder
Given two inputs of Half Adder A, B. The task is to implement the Half Adder circuit and Print output i.e
sum and carry of two inputs
Logical Expression:
Sum = A XOR B
Carry = A AND B
Truth Table:
Logical Expression :
SUM = C-IN XOR ( A XOR B )
C-0UT= A B + B C-IN + A C-IN
Truth Table :
# Driver code
A=0
B=0
C=1
# passing three inputs of fulladder as arguments to get result function
full_adder(A, B, C)
Parallel Adder
A Parallel Adder is a digital circuit capable of finding the arithmetic sum of two binary numbers that
is greater than one bit in length by operating on corresponding pairs of bits in parallel.
def binary_adder(a,b):
an = len(a)
bn = len(b)
print(al)
print(bl)
result = []
carry = 0
# Iterate through list right to left, calling full_adder each time and
# inserting the sum each time
for i in range(len(al)-1,-1,-1):
carry,sum = full_adder(carry,al[i],bl[i])
result.insert(0,sum)
print result
result.insert(0,carry)