R22 Python Manual (1)
R22 Python Manual (1)
OF
COMPUTER SCIENCE & ENGNEERING
PYTHON
PROGRAMMING
LABORATORY
(Course Code: 22CS1251)
MASTER MANUAL
2022-23
(R22 Regulation)
B.TECH I YEAR II SEM
Prepared By
A.sandhya
1
1. GUIDELINES TO STUDENTS
1. Equipment in the lab for the use of student community. Students need to maintain a proper
decorum in the computer lab. Students must use the equipment with care. Any damage is caused is
punishable.
3. Students are supposed to occupy the systems allotted to them and are not supposed to talk or
make noise in the lab.
4. Students are required to carry their observation book and lab records with completedexercises
while entering the lab.
2
1. Course Objectives:
1. To learn python programming language using the data types, input/ output statements.
2. To install and run the Python interpreter
3. To learn control structures.
4. To Understand Lists, Dictionaries in python
5. To Handle Strings and Files inPython
2.Course Outcomes:
After completion of the course, the student should be able to
1. Develop the application specific codes using python.
2. Understand Strings, Lists, Tuples and Dictionaries in Python
3. Verify programs using modular approach, file I/O, Python standard library
4. Implement Digital Systems using Python
5. Capable to implement on hardwareboards
There are 30 systems (HP) installed in this Lab. Their configurations are asfollows:
Processor : Pentium(R) Dual-Core CPU E5700 @
3.00GHz
RAM : 1 GB
Hard Disk : 320 GB
Mouse : Optical Mouse
3
4. List of experiments as per the Uuniversity curriculum
INDEX
WEEK Program Title Page No
4
1. Write a function called is_sorted that takes a list as a 19-27
parameter and returns True if the list is sorted in ascending
4 order and False otherwise.
2. 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.
3. 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 functionthat takes a sentence as an input
parameter and replaces thefirst letter of every word with
the corresponding upper caseletter 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
28-33
1. i) Write a python program that defines a matrix and prints
5
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. 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.
5
6 1. a. Write a function called draw_rectangle that takes a 34-38
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.
7 39-46
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.
8 47-44
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.
6
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.
7
2. Start a Python interpreter and use it as a Calculator.
8
3. i) Write a program to calculate compound interest when principal, rate and
number of periods are given.
Program:
# Python3 program to find compound
# interest for given values.
# Driver Code
compound_interest(10000, 10.25, 5)
output:
9
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
program:
import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)
output:
9
4. Read name, address, email and phone number of a person through keyboard
and print the details.
Program:
10
Week - 2:
1. Print the below triangle using for loop.
5
44
333
2222
11111
program:
output:
11
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)
program:
ch = input("Enter a character: ")
if ch >= '0' and ch <= '9':
print("Digit")
elif ch.isupper ():
print("Uppercase character")
elif ch.islower ():
print("Lowercase character")
else:
print("Special character")
output:
12
3. Python Program to Print the Fibonacci sequence using while loop
program:
output:
13
4. Python program to print all prime numbers in a given interval (use break)
program:
output:
14
Week - 3:
program:
import array
list1 = [3, 4, 5, 6]
my_array = array.array('i',list1)
print(my_array)
output:
array('i', [3, 4, 5, 6])
import array
tpl = (3, 4, 5, 6)
lst=list(tpl)
my_array = array.array('i',lst)
print(my_array)
output:
array('i', [3, 4, 5, 6])
15
ii) Write a program to find common values between two arrays.
program:
def find_common_values(array1, array2):
common_values = []
for value in array1:
if value in array2:
common_values.append(value)
return common_values
if __name__ == "__main__":
# Get the array values from the user.
print("Enter the values for the first array:")
array1 = list(map(int, input().split()))
print("Enter the values for the second array:")
array2 = list(map(int, input().split()))
output:
Enter the values for the first array:
2345
Enter the values for the second array:
3578
The common values between the two arrays are: [3, 5]
Write a function called gcd that takes parameters a and b and returns their
greatest common divisor.
program:
# Everything divides 0
if (a == 0):
return b
if (b == 0):
return a
16
# base case
if (a == b):
return a
# a is greater
if (a > b):
return gcd(a-b, b)
return gcd(a, b-a)
output:
17
2. 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:
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if len(word) <= 2 and word[0] == word[-1]:
print("entered string is palindrome")
elif word[0] == word[-1]:
is_palindrome(word[1:-1])
else:
print("entered string is not an palindrome")
is_palindrome(word)
output:
Enter a String: madam
entered string is palindrome
18
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.
program:
def is_sorted(listik):
if sorted(listik) == listik:
return True
else:
return False
print(is_sorted([1,2,2]))
print(is_sorted([1,2,1,2]))
print(is_sorted([]))
print(is_sorted(['a','b']))
print(is_sorted(['b','a']))
#END
output:
True
False
True
True
False
19
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.
program:
def has_duplicates(li):
if len(li) == 0:
return "List is empty."
elif len(li) == 1:
return "List contains only one element."
previous_elem = li[0]
for elem in sorted(li):
if previous_elem == elem:
return True
previous_elem = elem
return False
t = [4, 7, 2, 7, 3, 8, 9 ]
print(has_duplicates(t))
print(has_duplicates(['b', 'd', 'a', 't']))
print(has_duplicates([]))
print(has_duplicates(['']))
print(has_duplicates([5, 7, 9, 2, 1, 1, 8,]))
output:
True
False
List is empty.
List contains only one element.
True
20
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.
program:
def remove_duplicates(t):
"""Return new list with only unique elements."""
a = []
for i in t:
if i not in a:
a.append(i)
return a
s =[1, 2, 3, 2, 2, 5, 6, 6, 8, 8]
a = remove_duplicates(s)
print(a)
output:
[1, 2, 3, 5, 6, 8]
21
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.
# initializing dictionary
old_dict = {'A': 67, 'B': 23, 'C': 45, 'E': 12, 'F': 69, 'G': 67, 'H': 23}
print()
new_dict = {}
for key, value in old_dict.items():
if value in new_dict:
new_dict[value].append(key)
else:
new_dict[value]=[key]
output:
Original dictionary is :
{'A': 67, 'B': 23, 'C': 45, 'E': 12, 'F': 69, 'G': 67, 'H': 23}
22
3. i) Add a comma between the characters. If the given word is 'Apple', it should
become 'A,p,p,l,e'
program:
x = input("Enter a string:")
y=''
for i in x:
y += i + ','*1
y = y.strip()
print(repr(y))
output:
Enter a string:b.tech students
'b,.,t,e,c,h, ,s,t,u,d,e,n,t,s,'
23
ii) Remove the given word in all the places in a string?
program:
a1 = input("Enter a string:")
a2 = a1.replace(input("Enter a string to remove in main string:"), '')
print(a2)
output:
Enter a string:abcdefdgdtdfd
Enter a string to remove in main string:d
abcefgtf
24
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:
import re
def convert_into_uppercase(a):
return a.group(1) + a.group(2).upper()
s = input("enter an sentence or string: ")
result = re.sub("(^|\s)(\S)", convert_into_uppercase, s)
print(result)
output:
enter an sentence or string: python is an open-source programming language
Python Is An Open-source Programming Language
25
4. Writes a recursive function that generates all binary strings of n-bit length
program:
# 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
output:
0000
0001
0010
0011
26
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
27
Week - 5:
program:
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
output:
Enter the number of rows:2
Enter the number of columns:2
Enter the entries rowwise:
1
2
3
4
12
34
28
ii) Write a python program to perform addition of two square matrices
program:
program:
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:
print(r)
output:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
29
iii) Write a python program to perform multiplication of two square matrices
program:
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for r in result:
print(r)
output:
30
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.
program:
import tkinter as tk
master = tk.Tk()
def rectangle(event):
w.create_rectangle(event.x, event.y, event.x + 10, event.y + 10, fill="blue")
master.bind("<Button-1>", rectangle)
master.mainloop()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import tkinter as tk
master = tk.Tk()
def rectangle(event):
w.create_rectangle(event.x, event.y, event.x + 10, event.y + 10, fill="blue")
master.mainloop()
32
3. Use the structure of exception handling all general purpose exceptions.
Program:
def fun(a):
if a < 4:
try:
fun(3)
fun(5)
output:
ZeroDivisionError Occurred and Handled
33
Week-6:
program:
import tkinter as tk
master = tk.Tk()
def rectangle(event):
w.create_rectangle(event.x, event.y, event.x + 10, event.y + 10, fill="blue")
master.bind("<Button-1>", rectangle)
master.mainloop()
output:
https://www.studocu.com/in/document/sreenidhi-institute-of-science-and-technology/bachelor-of-technology-
electronics-and-electrical-engineering/psp-lm/46681253
34
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
program:
import tkinter as tk
root=tk.Tk()
Canvas=tk.Canvas(root,width=400,height=400)
Canvas.pack()
Canvas.create_rectangle(0,0,100,100,fill='red')
root.mainloop()
output:
35
2. Write a Python program to demonstrate the usage of Method Resolution
Order (MRO) in multiple levels of Inheritances.
class Mammal:
def mammal_info(self):
print("Mammals can give direct birth.")
class WingedAnimal:
def winged_animal_info(self):
print("Winged animals can flap.")
b1.mammal_info()
b1.winged_animal_info()
output:
36
3. Write a python code to read a phone number and email-id from the user
and validate it for correctness.
import re
else:
print("Invalid Email")
# Driver Code
if name == ' main ':
def isValid(s):
# 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(s)
# Driver Code
s = input("Enter u r Mobile Number: ")
if (isValid(s)):
37
print ("Valid Number")
else :
print ("Invalid Number")
output:
38
Week- 7
1. Write a Python code to merge two given file contents into a third file.
program:
# Python program to
# demonstrate merging
# of two files
# Merging 2 files
# To add the data of file2
# from next line
data += "\n"
data += data2
39
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.
program:
# Python program to read
# file word by word
output:
40
3. Write a Python code to Read text from a text file, find the word with most
number of occurrences
program:
# Open the file in read mode
text = open("file4.txt", "r")
output:
41
42
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.
43
no.of vowels:
program:
def counting(filename):
output:
44
blank spaces:
program:
# this will open the file and store
# in "file" variable
file = open("file2.txt", "r")
count = 0
while True:
if char.isspace():
count += 1
if not char:
break
print(count)
output:
45
to display uppercase and lower case
program:
with open("file2.txt") as file:
count = 0
countlower = 0
text = file.read()
for i in text:
if i.isupper():
count += 1
if i.islower():
countlower += 1
print(count)
print(countlower)
output:
46
Week - 8:
Python NumPy is a general-purpose array processing package that provides tools for handling n-
dimensional arrays. It provides various computing tools such as comprehensive mathematical
functions, linear algebra routines. NumPy provides both the flexibility of Python and the speed of
well-optimized compiled C code. Its easy-to-use syntax makes it highly accessible and productive
for programmers from any background.
Pre-requisites:
The only thing that you need for installing Numpy on Windows are:
Python
PIP or Conda (depending upon user preference)
Users who prefer to use pip can use the below command to install NumPy:
pip install numpy
You will get a similar message once the installation is complete:
Now that we have installed Nump y successfully in our system, let’s take a look at few simple
examples.
47
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
AND:
def AND (a, b):
if a == 1 and b == 1:
return True
else:
return False
# Driver code
if name ==' main ':
print(AND(1, 1))
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)," | ")
OUTPUT:
True
+ + +
| AND Truth Table | Result |
A = False, B = False | A AND B = False |
A = False, B = True | A AND B = False |
A = True, B = False | A AND B = False |
A = True, B = True | A AND B = True |
48
OR:
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)," | ")
OUTPUT:
False
+ + +
| OR Truth Table | Result |
A = False, B = False | A OR B = False |
A = False, B = True | A OR B = True |
A = True, B = False | A OR B = True |
A = True, B = True | A OR B = True |
49
NOT:
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)," | ")
OUTPUT:
True
+ + +
| NOT Truth Table | Result |
A = False | A NOT = True |
A = True, | A NOT = False |
50
XOR:
def XOR (a, b):
if a != b:
return 1
else:
return 0
# 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)," | ")
OUTPUT:
0
+ + +
| XOR Truth Table | Result |
A = False, B = False | A XOR B = 0 |
A = False, B = True | A XOR B = 1 |
A = True, B = False | A XOR B = 1 |
A = True, B = True | A XOR B = 0 |
51
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
HALF ADDER:
def getResult(A, B):
# Driver code
A=0
B=1
OUTPUT:
Sum 1
Carry 0
52
FULL ADDER:
# Driver code
A=0
B=0
C=1
# passing three inputs of fulladder as arguments to get result function
getResult(A, B, C)
53
5. Write a GUI program to create a window wizard having two text labels, two
text fields and two buttons as Submit and Reset
def write_text():
print("Tkinter is easy to create GUI!")
parent = tk.Tk()
frame = tk.Frame(parent)
frame.pack()
text_disp= tk.Button(frame,
text="Hello",
command=write_text
)
text_disp.pack(side=tk.LEFT)
exit_button = tk.Button(frame,
text="Exit",
fg="green",
command=quit)
exit_button.pack(side=tk.RIGHT)
parent.mainloop()
Sample Output:
54