Python programming lab manual
Python programming lab manual
Introduction to Python
Python is a widely used general-purpose, high level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation.
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python.
Indentation in Python is used to create a group of statements that are executed as a block. Many
popular languages such as C, and Java uses braces ({ }) to define a block of code, and Python uses
indentation.
The four whitespaces or a single tab character at the beginning of a code line are used to create or
increase the indentation level.
Let’s look at an example to understand the code indentation and grouping of statements.
def foo():
Page 1 of 61
R22 PYTHON PROGRAMMING LAB
4. It’s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
5. It’s Portable
Python runs virtually every major platform used today.
As long as you have a compaitable python interpreter installed, python programs will run in
exactly the same manner, irrespective of platform.
7. Interpreted Language
Python is processed at runtime by python Interpreter
Page 2 of 61
R22 PYTHON PROGRAMMING LAB
Page 3 of 61
R22 PYTHON PROGRAMMING LAB
List
Lists are used to store multiple items in a single variable.
Lists are created using square brackets:
List Length
To determine how many items a list has, use the len() function:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output: 3
Example
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
Python Tuples
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Python Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
Page 4 of 61
R22 PYTHON PROGRAMMING LAB
Page 5 of 61
R22 PYTHON PROGRAMMING LAB
WEEK 1:
3.
i). Write a program to calculate compound interest when principal,
rate and number of periods are given.
CODE:
def compound_interest(principle, rate, time):
# Driver Code
#Taking input from user.
principle = int(input("Enter the principle amount: "))
rate = int(input("Enter rate of interest: "))
time = int(input("Enter time in years: " ))
#Function Call
compound_interest(principle,rate,time)
OUTPUT:
ii). Given coordinates (x1, y1), (x2, y2) find the distance between two
points
CODE:
import math
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
Page 6 of 61
R22 PYTHON PROGRAMMING LAB
OUTPUT:
enter x1 : 4
enter x2 : 6
enter y1 : 0
enter y2 : 6
distance between (4, 6) and (0, 6) is : 6.324555320336759
CODE:
print("Enter your name: ", end="")
name = input()
OUTPUT:
Enter your name: Raj
Enter your address: Karimnagar
Enter your email: rajashekart90@gmail.com
Enter your contact: 9700559986
Name: Raj
Address: Karimnagar
Page 7 of 61
R22 PYTHON PROGRAMMING LAB
Email: rajashekart90@gmail.com
Contact: 9700559986
Page 8 of 61
R22 PYTHON PROGRAMMING LAB
WEEK - 2:
5
44
333
2222
11111
CODE:
for i in range(5,0,-1):
for j in range(i,6):
print()
OUTPUT:
5
44
333
2222
11111
Page 9 of 61
R22 PYTHON PROGRAMMING LAB
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)
CODE:
print("Digit")
print("Uppercase character")
print("Lowercase character")
else:
print("Special character")
OUTPUT:
Hello World
Enter a character: @
Special character
Page 10 of 61
R22 PYTHON PROGRAMMING LAB
CODE:
n1 = 0
n2 = 1
Sum = 0
i=0
Next = n1 + n2
n1 = n2
n2 = Next
i=i+1
OUTPUT:
Page 11 of 61
R22 PYTHON PROGRAMMING LAB
4. Python program to print all prime numbers in a given interval (use break)
CODE:
OUTPUT:
Page 12 of 61
R22 PYTHON PROGRAMMING LAB
WEEK-3
1.
i) Write a program to convert a list and tuple into arrays.
import numpy as np
# list
list1 = [3, 4, 5, 6]
print(type(list1))
print(list1)
print()
# conversion
array1 = np.asarray(list1)
print(type(array1))
print(array1)
print()
# tuple
# conversion
array2 = np.asarray(tuple1)
print(type(array2))
print(array2)
OUTPUT:
<class 'list'>
[3, 4, 5, 6]
<class 'numpy.ndarray'>
[3 4 5 6]
<class 'tuple'>
([8, 4, 6], [1, 2, 3])
<class 'numpy.ndarray'>
[[8 4 6]
[1 2 3]]
Page 13 of 61
R22 PYTHON PROGRAMMING LAB
CODE:
import numpy as np
OUTPUT:
[1 3 4]
Page 14 of 61
R22 PYTHON PROGRAMMING LAB
2. Write a function called gcd that takes parameters a and b and returns their
greatest common divisor.
CODE 1:
import math
# prints 12
print("The gcd of 60 and 48 is : ", end="")
print(math.gcd(60, 48))
OUTPUT:
The gcd of 60 and 48 is : 12
CODE 2:
a = 60
b = 48
# prints 12
print("The gcd of 60 and 48 is : ", end="")
print(hcf(60, 48))
OUTPUT:
The gcd of 60 and 48 is : 12
Page 15 of 61
R22 PYTHON PROGRAMMING LAB
CODE 1:
def isPalindrome(str):
# main function
s = "malayalam"
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
OUTPUT:
Yes
CODE 2:
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
OUTPUT:
Yes
Page 16 of 61
R22 PYTHON PROGRAMMING LAB
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(user_list):
return user_list == sorted (user_list)
user_list=input("Please enter a list: ")
user_list = user_list.split()
print(is_sorted(user_list))
print("Your list: ", user_list)
OUTPUT:
Please enter a list: 1 3 6 9
True
Your list: ['1', '3', '6', '9']
Please enter a list: 15 7 2 20
False
Your list: ['15', '7', '2', '20']
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.
OUTPUT:
True
None
Page 17 of 61
R22 PYTHON PROGRAMMING LAB
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(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:
Page 18 of 61
R22 PYTHON PROGRAMMING LAB
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}
Page 19 of 61
R22 PYTHON PROGRAMMING LAB
output:
A,p,p,l,e
x = "Apple"
y=''
for i in x:
y += i + ','*1
y = y.strip()
print(repr(y))
OUTPUT:
A,p,p,l,e
output:
A,p,p,l,e
Page 20 of 61
R22 PYTHON PROGRAMMING LAB
OUTPUT:
import re
a1 = "remove word from this"
. p = re.compile('(\s*)word(\s*)')
a2 = p.sub(' ', a1)
print(a2)
Output:
Page 21 of 61
R22 PYTHON PROGRAMMING LAB
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?
# Python3 program to convert first character
# uppercase in a sentence
def convert(s):
for i in range(len(s)):
# If it is in lower-case
if (ch[i] >= 'a' and ch[i] <= 'z'):
Page 22 of 61
R22 PYTHON PROGRAMMING LAB
return st;
# Driver code
if __name__=="__main__":
print(convert(s));
OUTPUT:
Geeks For Geeks
Page 23 of 61
R22 PYTHON PROGRAMMING LAB
print()
if i == n:
printTheArray(arr, n)
return
Page 24 of 61
R22 PYTHON PROGRAMMING LAB
# Driver Code
if __name__ == "__main__":
n=4
arr = [None] * n
Page 25 of 61
R22 PYTHON PROGRAMMING LAB
1100
1101
1110
1111
Page 26 of 61
R22 PYTHON PROGRAMMING LAB
Week - 5:
1.
# Initialize matrix
matrix = []
a =[]
a.append(int(input()))
matrix.append(a)
for i in range(R):
for j in range(C):
print()
output:
Page 27 of 61
R22 PYTHON PROGRAMMING LAB
123
456
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]]
Page 28 of 61
R22 PYTHON PROGRAMMING LAB
for i in range(len(X)):
for j in range(len(X[0])):
for r in result:
print(r)
output:
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
Page 29 of 61
R22 PYTHON PROGRAMMING LAB
[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 i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
for r in result:
print(r)
output:
Page 30 of 61
R22 PYTHON PROGRAMMING LAB
The basic operations of OpenCV is to draw over images. The ability to add
different geometric shapes just like lines, circles and rectangle etc.
Often working with image analysis, we want to highlight a portion of the image,
for example by adding a rectangle that defines that portion. Also as example an
arrow to indicate something.
cv2.line() − This function is used to draw line on an image.
cv2.rectangle() − This function is used to draw rectangle on an image.
cv2.circle() − This function is used to draw circle on an image.
cv2.putText() − This function is used to write text on image.
cv2.ellipse() − This function is used to draw ellipse on image.
TO DRAW A LINE
For drawing a line cv2.line() function is used. This function takes five arguments
import numpy as np
import cv2
my_img = np.zeros((350, 350, 3), dtype = "uint8")
# creating for line
cv2.line(my_img, (202, 220), (100, 160), (0, 20, 200), 10)
Page 31 of 61
R22 PYTHON PROGRAMMING LAB
cv2.imshow('Window', my_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
TO DRAW A RECTANGLE
For drawing a rectangle cv2.rectangle() function is used. This function accepts
five input parameters.
Page 32 of 61
R22 PYTHON PROGRAMMING LAB
import numpy as np
import cv2
my_img = np.zeros((400, 400, 3), dtype = "uint8")
# creating a rectangle
cv2.rectangle(my_img, (30, 30), (300, 200), (0, 20, 200), 10)
cv2.imshow('Window', my_img)
# allows us to see image
# until closed forcefully
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Page 33 of 61
R22 PYTHON PROGRAMMING LAB
TO DRAW A CIRCLE
For drawing a circle, cv2.circle() function is used. This function accepts five input
parameters.
import numpy as np
import cv2
my_img = np.zeros((400, 400, 3), dtype = "uint8")
# creating circle
cv2.circle(my_img, (200, 200), 80, (0, 20, 200), 10)
cv2.imshow('Window', my_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Page 34 of 61
R22 PYTHON PROGRAMMING LAB
Output
Page 35 of 61
R22 PYTHON PROGRAMMING LAB
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ", b)
try:
fun(3)
fun(5)
# multiple exceptions
except ZeroDivisionError:
except NameError:
OUTPUT:
Page 36 of 61
R22 PYTHON PROGRAMMING LAB
Week-6
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
Page 37 of 61
R22 PYTHON PROGRAMMING LAB
def draw_something(canvas):
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle([[-100, 60], [100, 60]], outline=None, fill='white')
drawn_canvas.rectangle([[-100, -60], [100, 0]], outline=None, fill='red2')
drawn_canvas.circle([100,100],50)
points = [[-100,-60], [-100, 60], [0, 0]]
drawn_canvas.polygon(points, fill='yellow')
world = World()
draw_something(a_canvas)
world.mainloop()
Output:
Page 38 of 61
R22 PYTHON PROGRAMMING LAB
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in
multiple levels of Inheritances.
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
In the above example the methods that are invoked is from class B but not from class A, and this is
due to Method Resolution Order(MRO).
The order that follows in the above code is- class B – > class A
In multiple inheritances, the methods are executed based on the order specified while inheriting the
classes.
Page 39 of 61
R22 PYTHON PROGRAMMING LAB
To get the method resolution order of a class we can use either __mro__ attribute or mro() method.
By using these methods we can display the order in which methods are resolved.
For Example
# Python program to show the order
# in which methods are resolved
class A:
def rk(self):
print(" In class A")
class B:
def rk(self):
print(" In class B")
# classes ordering
class C(A, B):
def __init__(self):
print("Constructor C")
r = C()
Output:
Constructor C
Page 40 of 61
R22 PYTHON PROGRAMMING LAB
WEEK-6:
3.Write a python code to read a phone number and email-id from the user
and validate it for correctness.
import re
regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'
def check(email):
if(re.fullmatch(regex, email)):
print("Valid Email")
else:
print("Invalid Email")
# Driver Code
if __name__ == '__main__':
email = "ankitrai326@gmail.com"
Page 41 of 61
R22 PYTHON PROGRAMMING LAB
check(email)
email = "my.ownsite@our-earth.org"
check(email)
email = "ankitrai326.com"
check(email)
OUTPUT:
Valid Email
Valid Email
Invalid Email
Page 42 of 61
R22 PYTHON PROGRAMMING LAB
WEEK-7
1. Write a Python code to merge two given files contents into a third file.
# Merging 2 files
# To add the data of file2
# from next line
data += "\n"
data += data2
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.
file = open("search.txt")
print(file.read())
search_word = input("enter a word you want to search in file: ")
if(search_word == file):
Page 43 of 61
R22 PYTHON PROGRAMMING LAB
print("word found")
else:
print("word not found")
3.Write a Python code to Read text from a text file, find the word with most
number of occurrences
Page 44 of 61
R22 PYTHON PROGRAMMING LAB
Output:
mango : 3
banana : 3
apple : 3
pear : 2
grapes : 1
strawberry : 2
kiwi : 1
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.
# Python program to count number of vowels,
# newlines and character in textfile
def counting(filename):
Page 45 of 61
R22 PYTHON PROGRAMMING LAB
Output:
Number of vowels in MyFile.txt = 23
New Lines in MyFile.txt = 2
Number of characters in MyFile.txt = 54
BLANK SPACES:
Page 46 of 61
R22 PYTHON PROGRAMMING LAB
if tot>1:
print("\nThere are " + str(tot) + " Blank spaces available in the File")
elif tot==1:
print("\nThere is only 1 Blank space available in the File")
else:
print("\nThere is no any Blank space available in the File!")
except IOError:
print("\nError Occurred!")
COUNT VOWELS:
print("Enter the Name of File: ")
fileName = str(input())
fileHandle = open(fileName, "r")
tot = 0
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
Page 47 of 61
R22 PYTHON PROGRAMMING LAB
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Vivek")
NumPy
NumPy is a Python library.
NumPy is used for working with arrays.
NumPy is short for "Numerical Python".
Example
Create a NumPy array:
import numpy as np
print(arr)
print(type(arr))
Page 48 of 61
R22 PYTHON PROGRAMMING LAB
Output: [1 2 3 4 5]
<class 'numpy.ndarray'>
SciPy
SciPy is a scientific computation library that uses NumPy
underneath.
SciPy stands for Scientific Python.
It provides more utility functions for optimization, stats and
signal processing.
Like NumPy, SciPy is open source so we can use it freely.
SciPy was created by NumPy's creator Travis Olliphant.
SciPy has optimized and added functions that are frequently used
in NumPy and Data Science.
Example
How many cubic meters are in one liter:
from scipy import constants
print(constants.liter)
Output: 0.001
Constants in SciPy
As SciPy is more focused on scientific implementations, it provides many built-in scientific
constants.
These constants can be helpful when you are working with Data Science.
Constant Units
A list of all units under the constants module can be seen using the dir() function.
Unit Categories
The units are placed under these categories:
• Metric
• Binary
• Mass
• Angle
• Time
Page 49 of 61
R22 PYTHON PROGRAMMING LAB
• Length
• Pressure
• Volume
• Speed
• Temperature
• Energy
• Power
• Force
Matplotlib
Matplotlib is a low level graph plotting library in python that
serves as a visualization utility.
Matplotlib was created by John D. Hunter.
Matplotlib is open source and we can use it freely.
Matplotlib is mostly written in python, a few segments are written in C, Objective-C and Javascript
for Platform compatibility.
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:
import matplotlib.pyplot as plt
Example
Draw a line in a diagram from position (0,0) to position (6,250):
import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
Page 50 of 61
R22 PYTHON PROGRAMMING LAB
Page 51 of 61
R22 PYTHON PROGRAMMING LAB
WEEK - 8:
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-
OR
if a == 1 and b == 1:
return True
else:
return False
# Driver code
if __name__=='__main__':
print(AND(1, 1))
print("+---------------+----------------+")
OUTPUT:
True
+---------------+----------------+
Page 52 of 61
R22 PYTHON PROGRAMMING LAB
# working of OR gate
if a == 1 or b ==1:
return True
else:
return False
# Driver code
if __name__=='__main__':
print(OR(0, 0))
print("+---------------+----------------+")
Page 53 of 61
R22 PYTHON PROGRAMMING LAB
OUTPUT:
False
+---------------+----------------+
if a != b:
return 1
else:
return 0
# Driver code
Page 54 of 61
R22 PYTHON PROGRAMMING LAB
if __name__=='__main__':
print(XOR(5, 5))
print("+---------------+----------------+")
OUTPUT:
TRUE
+---------------+----------------+
def NOT(a):
return not a
Page 55 of 61
R22 PYTHON PROGRAMMING LAB
# Driver code
if __name__=='__main__':
print(NOT(0))
print("+---------------+----------------+")
OUTPUT:
True
+---------------+----------------+
Sum = A ^ B
Page 56 of 61
R22 PYTHON PROGRAMMING LAB
Carry = A & B
print("Carry", Carry)
# Driver code
A=0
B=1
getResult(A, B)
OUTPUT:
Sum 1
Carry 0
Page 57 of 61
R22 PYTHON PROGRAMMING LAB
Logical Expression:
Sum = A XOR B
Carry = A AND B
Using numpy:
Algorithm:
import numpy as np
def half_adder(A, B):
Sum = np.bitwise_xor(A, B)
Carry = np.bitwise_and(A, B)
return Sum, Carry
A =0
B =1
Page 58 of 61
R22 PYTHON PROGRAMMING LAB
Installing swampy
sudo pip install swampy
5. Write a GUI program to create a window wizard having two text labels, two text fields and two
buttons as Submit and Reset.
Page 59 of 61
R22 PYTHON PROGRAMMING LAB
window = Tk()
window.geometry('350x200')
lbl.grid(column=0, row=0)
lbl1.grid(column=0, row=1)
txt = Entry(window,width=10)
txt.grid(column=1, row=0)
txt1 = Entry(window,width=10)
txt1.grid(column=1, row=1)
def clicked():
Page 60 of 61
R22 PYTHON PROGRAMMING LAB
lbl.configure(text= res)
lbl1.configure(text= res)
window.mainloop()
Page 61 of 61