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

Python programming lab manual

The document provides an introduction to Python programming, highlighting its features such as object-oriented structure, ease of use, and portability. It covers various data types including lists, tuples, sets, and dictionaries, along with examples and exercises for practical application. Additionally, it includes programming tasks for calculating compound interest, finding distances, and manipulating arrays, among others.

Uploaded by

sanashashikanth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Python programming lab manual

The document provides an introduction to Python programming, highlighting its features such as object-oriented structure, ease of use, and portability. It covers various data types including lists, tuples, sets, and dictionaries, along with examples and exercises for practical application. Additionally, it includes programming tasks for calculating compound interest, finding distances, and manipulating arrays, among others.

Uploaded by

sanashashikanth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

R22 PYTHON PROGRAMMING LAB

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.

Why to use Python?

The following are the primary factors to use python i:

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

3. It’s free (open source)


Downloading python and installing python is free and easy

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.

6. It’s easy to use and learn


 No intermediate compile.
 Python Programs are compiled automatically to an intermediate form called byte code, which the
interpreter then reads.
 This gives python the development speed of an interpreter without the performance loss inherent
in purely interpreted languages.
 Structure and syntax are pretty intuitive and easy to grasp.

7. Interpreted Language
Python is processed at runtime by python Interpreter

8. Interactive Programming Language


Users can interact with the python interpreter directly for writing the programs

9. Straight forward syntax


The formation of python syntax is simple and straight forward which also makes it
popular.

Page 2 of 61
R22 PYTHON PROGRAMMING LAB

Python Collections (Arrays)


There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
• Dictionary is a collection which is ordered** and changeable. No duplicate members.

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:

thislist = ["apple", "banana", "cherry"]


print(thislist)

Output: ['apple', 'banana', 'cherry']

List Length
To determine how many items a list has, use the len() function:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

Output: 3

A list can contain different data types:

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)

Output: ('apple', 'banana', 'cherry')

Tuple items are ordered, unchangeable, and allow duplicate values.


Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

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

Create and print a dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

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

# Calculates compound interest


Amount = principle * (pow((1 + rate / 100), time))
CI = Amount - principle
print("Compound interest is", CI)

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

Enter the principal amount: 10000


Enter rate of interest: 1
Enter time in years: 1
Compound interest is 100.0

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

result= math.sqrt( ((x2-x1)**2)+((y2-y1)**2) )


print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)

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

4. Read name, address, email and phone number of a person


through keyboard and print the details

CODE:
print("Enter your name: ", end="")
name = input()

print("Enter your address: ", end="")


address = input()

print("Enter your email: ", end="")


email = input()

print("Enter your contact: ", end="")


contact = input()

print("Name: ", name)


print("Address: ", address)
print("Email: ", email)
print("Contact: ", contact)

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:

1. Print the below triangle using for loop.

5
44
333
2222
11111

CODE:
for i in range(5,0,-1):

for j in range(i,6):

print(i, end=' ')

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:

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:

Hello World

Enter a character: @

Special character

Page 10 of 61
R22 PYTHON PROGRAMMING LAB

3. Python Program to Print the Fibonacci sequence using while loop

CODE:

num = int(input("Enter the Fibonacci Number Range: "))

n1 = 0
n2 = 1
Sum = 0
i=0

while(i < num):


print(n1, end = ' ')

Next = n1 + n2
n1 = n2
n2 = Next
i=i+1

OUTPUT:

Enter the Fibonacci Number Range: 5


0 1 1 2 3

Page 11 of 61
R22 PYTHON PROGRAMMING LAB

4. Python program to print all prime numbers in a given interval (use break)

CODE:

start=int(input("enter starting value : "))


end=int(input("enter ending value : "))
print("Prime numbers between", start, "and", end, "are:")
for num in range(start, end + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

OUTPUT:

enter starting value : 0


enter ending value : 10
Prime numbers between 0 and 10 are:
2
3
5
7

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

tuple1 = ([8, 4, 6], [1, 2, 3])


print(type(tuple1))
print(tuple1)
print()

# 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

ii) Write a program to find common values between two arrays.

CODE:
import numpy as np

ar1 = np.array([0, 1, 2, 3, 4])


ar2 = [1, 3, 4]

# Common values between two arrays


print(np.intersect1d(ar1, ar2))

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:

def hcf(a, b):


if(b == 0):
return a
else:
return hcf(b, a % b)

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

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.

CODE 1:
def isPalindrome(str):

# Run loop from 0 to len/2


for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True

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

def common_data(list1, list2):


result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [5,6,7,8,9]))
print(common_data([1,2,3,4,5], [6,7,8,9]))

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:

[2, 4, 10, 20, 5]

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}

# Printing original dictionary


print ("Original dictionary is : ")
print(old_dict)

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]

# Printing new dictionary after swapping


# keys and values
print ("Dictionary after swapping is : ")
print("keys: values")
for i in new_dict:
print(i, " :", new_dict[i])

OUTPUT:
Original dictionary is :
{'A': 67, 'B': 23, 'C': 45, 'E': 12, 'F': 69, 'G': 67, 'H': 23}

Dictionary after swapping is :


keys: values
67 : ['A', 'G']
23 : ['B', 'H']
45 : ['C']
12 : ['E']
69 : ['F']

Page 19 of 61
R22 PYTHON PROGRAMMING LAB

3 i) Add a comma between the characters. If the given word is 'Apple',


it should become 'A,p,p,l,e'

Using the join () function.


x = "Apple"
y = ','.join(x)
print(y)

output:
A,p,p,l,e

Using a for loop.

x = "Apple"
y=''
for i in x:
y += i + ','*1
y = y.strip()
print(repr(y))

OUTPUT:
A,p,p,l,e

Using the replace() function.


x = "Apple"
def commaez(x):
return x.replace('',',')[1:-1]
print(commaez(x))

output:
A,p,p,l,e

Page 20 of 61
R22 PYTHON PROGRAMMING LAB

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


Using the replace() function

a1 = "remove word from this"


a2 = a1.replace("word", '')
print(a2)

OUTPUT:

remove from this


Using the re.sub() function

import re
a1 = "remove word from this"
. p = re.compile('(\s*)word(\s*)')
a2 = p.sub(' ', a1)
print(a2)

Output:

remove from this

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

# Create a char array of


# given string
ch = list(s)

for i in range(len(s)):

# If first character of a word is found


if (i == 0 and ch[i] != ' ' or
ch[i] != ' ' and
ch[i - 1] == ' '):

# If it is in lower-case
if (ch[i] >= 'a' and ch[i] <= 'z'):

# Convert into Upper-case


ch[i] = chr(ord(ch[i]) - ord('a') +
ord('A'))

Page 22 of 61
R22 PYTHON PROGRAMMING LAB

# If apart from first character


# Any one is in Upper-case
elif (ch[i] >= 'A' and ch[i] <= 'Z'):

# Convert into Lower-Case


ch[i] = chr(ord(ch[i]) + ord('a') -
ord('A'))

# Convert the char array


# to equivalent string
st = "".join(ch)

return st;

# Driver code
if __name__=="__main__":

s = "gEEks fOr GeeKs"

print(convert(s));

OUTPUT:
Geeks For Geeks

Page 23 of 61
R22 PYTHON PROGRAMMING LAB

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


length

# Python3 implementation of the


# above approach
# Function to print the output
def printTheArray(arr, n):
for i in range(0, n):
print(arr[i], end = " ")

print()

# Function to generate all binary strings


def generateAllBinaryStrings(n, arr, i):

if i == n:
printTheArray(arr, n)
return

# First assign "0" at ith position


# and try for all other permutations
# for remaining positions
arr[i] = 0
generateAllBinaryStrings(n, arr, i + 1)

# And then assign "1" at ith position

Page 24 of 61
R22 PYTHON PROGRAMMING LAB

# and try for all other permutations


# for remaining positions
arr[i] = 1
generateAllBinaryStrings(n, arr, i + 1)

# Driver Code
if __name__ == "__main__":

n=4
arr = [None] * n

# Print all binary strings


generateAllBinaryStrings(n, arr, 0)
OUTPUT:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011

Page 25 of 61
R22 PYTHON PROGRAMMING LAB

1100
1101
1110
1111

Page 26 of 61
R22 PYTHON PROGRAMMING LAB

Week - 5:
1.

i) Write a python program that defines a matrix and prints

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:

Page 27 of 61
R22 PYTHON PROGRAMMING LAB

Enter the number of rows:2

Enter the number of columns:3

Enter the entries rowwise:

123

456

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

# Program to add two matrices using nested loop

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

# iterate through rows

for i in range(len(X)):

# iterate through columns

for j in range(len(X[0])):

result[i][j] = X[i][j] + Y[i][j]

for r in result:

print(r)

output:

[10, 10, 10]

[10, 10, 10]

[10, 10, 10]

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

# Program to multiply two matrices using nested loop

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

# iterate through rows of X

for i in range(len(X)):

# iterate through columns of Y

for j in range(len(Y[0])):

# iterate through rows of Y

for k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]

for r in result:

print(r)

output:

[114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]

Page 30 of 61
R22 PYTHON PROGRAMMING LAB

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.

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

 Image object on which to draw


 Starting point coordinates (x, y)
 End point coordinates (x, y)
 Stroke color in BGR (not RGB, to be noted)
 Stroke thickness (in pixels)

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.

 Image object on which to draw


 Coordinates of the vertex at the top left (x, y)
 Coordinates of the lower right vertex (x, y)
 Stroke color in BGR (not RGB, to be noted)
 Stroke thickness (in pixels)

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.

 Image object on which to draw


 Center coordinates (x, y)
 Radius of the circle
 Stroke color in BGR (not RGB, to be noted)
 Stroke thickness (in pixels)

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

3.Use the structure of exception handling all general purpose exceptions

def fun(a):

if a < 4:

# throws ZeroDivisionError for a = 3

b = a/(a-3)

# throws NameError if a >= 4

print("Value of b = ", b)

try:

fun(3)

fun(5)

# note that braces () are necessary here for

# multiple exceptions

except ZeroDivisionError:

print("ZeroDivisionError Occurred and Handled")

except NameError:

print("NameError Occurred and Handled")

OUTPUT:

ZeroDivisionError Occurred and Handled

Page 36 of 61
R22 PYTHON PROGRAMMING LAB

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.

from swampy.TurtleWorld import *


class Point(object):
"represents a point in 2-D space"
p = Point()
p.x = 60
p.y = 15
class Rectangle(object):
"""Represents a rectangle."""
box = Rectangle()
box.color = 'blue'
box.bbox = [[-100, -60],[100, 60]]
class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
a_canvas = Canvas()
a_canvas.width = 500
a_canvas.height = 500

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_rectangle(canvas, rectangle):


drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle(rectangle.bbox, fill=rectangle.color)

def draw_point(canvas, point):


bbox = [[point.x, point.y], [point.x, point.y]]

Page 37 of 61
R22 PYTHON PROGRAMMING LAB

drawn_canvas = world.ca(canvas.width, canvas.height)


drawn_canvas.rectangle(bbox, fill="black")

def draw_circle(canvas, circle):


drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.circle([circle.center.x, circle.center.y], circle.radius)

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.

Method Resolution Order (MRO) in Python


Method Resolution Order(MRO) it denotes the way a programming language resolves a method or
attribute.
Python supports classes inheriting from other classes.
The class being inherited is called the Parent or Superclass, while the class that inherits is called the
Child or Subclass.
In python, method resolution order defines the order in which the base classes are searched when
executing a method.
First, the method or attribute is searched within a class and then it follows the order we specified
while inheriting.
This order is also called Linearization of a class and set of rules are called
MRO(Method Resolution Order).
While inheriting from another class, the interpreter needs a way to resolve the methods that are
being called via an instance.
Thus we need the method resolution order.
Example:
# Python program showing
# how MRO works

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

Methods for Method Resolution Order(MRO) of a class:

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

# it prints the lookup order


print(C.__mro__)
print(C.mro())

Output:

Constructor C

(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class


'object'>)

[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class


'object'>]

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

# Make a regular expression

# for validating an Email

regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'

# Define a function for

# for validating an Email

def check(email):

# pass the regular expression

# and the string into the fullmatch() method

if(re.fullmatch(regex, email)):

print("Valid Email")

else:

print("Invalid Email")

# Driver Code

if __name__ == '__main__':

# Enter the email

email = "ankitrai326@gmail.com"

# calling run function

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.

# Python program to demonstrate merging of two files

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)

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

# Open the file in read mode


text = open("sample.txt", "r")

# Create an empty dictionary


d = dict()

# Loop through each line of the file


for line in text:
# Remove the leading spaces and newline character
line = line.strip()

# Convert the characters in line to


# lowercase to avoid case mismatch
line = line.lower()

# Split the line into words


words = line.split(" ")

# Iterate over each word in line


for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1

# Print the contents of dictionary


for key in list(d.keys()):
print(key, ":", d[key])

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

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

Page 45 of 61
R22 PYTHON PROGRAMMING LAB

# 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
New Lines in MyFile.txt = 2
Number of characters in MyFile.txt = 54

BLANK SPACES:

print(end="Enter the Name of File: ")


fileName = str(input())
try:
fileHandle = open(fileName, "r")
tot = 0

Page 46 of 61
R22 PYTHON PROGRAMMING LAB

for char in fileHandle.read():


if char==' ':
tot = tot+1
fileHandle.close()

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

for char in fileHandle.read():


if char in vowels:
tot = tot+1
fileHandle.close()

print("\nTotal Vowels are:")


print(tot)

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

Output: Hello, 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

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

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

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

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

# Python3 program to illustrate

# working of AND gate

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

+---------------+----------------+

Page 52 of 61
R22 PYTHON PROGRAMMING LAB

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

#Python3 program to illustrate

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

Page 53 of 61
R22 PYTHON PROGRAMMING LAB

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 |

# Python3 program to illustrate

# working of Xor gate

def XOR (a, b):

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

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:

TRUE

+---------------+----------------+

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

# Python3 program to illustrate

# working of Not gate

def NOT(a):

return not a

Page 55 of 61
R22 PYTHON PROGRAMMING LAB

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

# Function to print sum and carry

def getResult(A, B):

# Calculating value of sum

Sum = A ^ B

# Calculating value of Carry

Page 56 of 61
R22 PYTHON PROGRAMMING LAB

Carry = A & B

# printing the values

print("Sum ", Sum)

print("Carry", Carry)

# Driver code

A=0

B=1

# passing two inputs of halfadder as arguments to get result function

getResult(A, B)

OUTPUT:

Sum 1

Carry 0

Page 57 of 61
R22 PYTHON PROGRAMMING LAB

4. Write a program to implement Half Adder,


Full Adder.
Python program to implement 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.
Half Adder: A half adder is a type of adder, an electronic circuit that performs the addition of
numbers. The half adder is able to add two single binary digits and provide the output plus a
carrying value. It has two inputs, called A and B, and two outputs S (sum) and C (carry).

Logical Expression:
Sum = A XOR B
Carry = A AND B

Using numpy:
Algorithm:

1. Import the required NumPy library.


2. Define the function half_adder(A, B) which takes two input bits A and B as arguments.
3. Calculate the Sum of the two input bits using the NumPy bitwise_xor() function which
returns the bitwise XOR of two input arrays.
4. Calculate the Carry of the two input bits using the NumPy bitwise_and() function which
returns the bitwise AND of two input arrays.
5. Return the calculated Sum and Carry values.
6. Define the input bits A and B.
7. Call the half_adder() function with the input bits A and B and store the returned Sum and
Carry values.
8. Print the calculated Sum and Carry values.

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

Sum, Carry = half_adder(A, B)


print("Sum:", Sum)
print("Carry:", Carry)

Python program to implement Full Adder


Given three inputs of Full Adder A, B,C-IN. The task is to implement the Full Adder circuit and
Print output i.e sum and C-Out of three inputs.
Full Adder : A Full Adder is a logical circuit that performs an addition operation on three one-bit
binary numbers. The full adder produces a sum of the three inputs and carry value.
Logical Expression :
SUM = C-IN XOR ( A XOR B )
C-0UT= A B + B C-IN + A C-IN

def getResult(A, B, C):


Sum = C ^ (A ^ B)
C
C_Out = Bin&(not(A ^ B))| not(A)&B
print("Sum = ", Sum)
print("C-Out = ", C_Out)
A =0
B =0
C =1
getResult(A, B, C)

Installing tkinter in ubuntu


sudo apt install python3-tk

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

from tkinter import *

window = Tk()

window.title("Welcome to Python Programming lab")

window.geometry('350x200')

lbl = Label(window, text="NAME")

lbl.grid(column=0, row=0)

lbl1 = Label(window, text="LAB")

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

res = "Hi " + txt.get()

Page 60 of 61
R22 PYTHON PROGRAMMING LAB

lbl.configure(text= res)

res = "Welcome to " + txt1.get()

lbl1.configure(text= res)

btn = Button(window, text="Submit", command=clicked, bg="BLACK", fg="red")


btn.grid(column=0, row=3)

window.mainloop()

Page 61 of 61

You might also like