0% found this document useful (0 votes)
4 views21 pages

Python LAB Programs-2

The document provides a series of Python programming exercises focused on drawing shapes on a canvas, implementing digital logic gates, validating user input, and exploring libraries such as NumPy and SciPy. Each exercise includes a program outline, aims, and results demonstrating successful execution. The content is structured to support learning in a Python programming laboratory context.

Uploaded by

sowgandhika8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views21 pages

Python LAB Programs-2

The document provides a series of Python programming exercises focused on drawing shapes on a canvas, implementing digital logic gates, validating user input, and exploring libraries such as NumPy and SciPy. Each exercise includes a program outline, aims, and results demonstrating successful execution. The content is structured to support learning in a Python programming laboratory context.

Uploaded by

sowgandhika8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING LABORATORY (PPL)

Regulation R22 - (I YEAR - II SEMESTER)


Programs (32-42):
32. Draw a representation of the Rectangle on the Canvas.

Aim: To write a python function called draw_rectangle that takes a Canvas and a
Rectangle as arguments and draws a representation of the Rectangle on the
Canvas.
To install package: pip install swampy (type in command prompt)
Program:
from [Link] import *
class Rectangle(object):
"""Represents a rectangle."""
class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
def draw_rectangle(canvas, rectangle):
drawn_canvas = [Link]([Link], [Link])
drawn_canvas.rectangle([Link])
r= Rectangle()
[Link] = [[-100, -60],[100, 60]] #left,top,right,bottom
c = Canvas()
[Link] = 500
[Link] = 500
world = World()
draw_rectangle(c,r)
[Link]()

Output:

Result: Thus, the python function to draw a representation of the Rectangle on the
Canvas has been executed successfully.
33. Draw a Rectangle on the Canvas and uses color attribute as the fill color.

Aim: To write a python function called draw_rectangle and add an attribute named
color to Rectangle object and modify draw_rectangle so that it uses the color
attribute as the fill color.
Program:
from [Link] import *
class Rectangle(object):
"""Represents a rectangle."""
class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
def draw_rectangle(canvas, rectangle):
drawn_canvas = [Link]([Link], [Link])
drawn_canvas.rectangle([Link], outline='red', fill=[Link],
width=5)
r= Rectangle()
[Link] = 'orange'
[Link] = [[-100, -60],[100, 40]]
c = Canvas()
[Link] = 500
[Link] = 500
world = World()
draw_rectangle(c,r)
[Link]()
Output:

Result: Thus, the python function to draw a rectangle and modify it uses by adding
the color attribute to fill the color has been executed successfully.
34. Draw a representation of the Point on the Canvas.

Aim: To write a python function called draw_point that takes a Canvas and a Point
as arguments and draws a representation of the Point on the Canvas.
Program:
from [Link] import *
class Point(object):
"represents a point in 2-D space"
class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
def draw_point(canvas, point):
points = [point.a,point.b,point.c,point.d,point.e,point.e,point.a,point.b]
drawn_canvas = [Link]([Link], [Link])
drawn_canvas.create_polygon(points, outline='darkgreen', fill="orange")
p = Point()
p.x = 250
p.y = 0
p.z = 500
p.a = 250
p.b = 110
p.c = 480
p.d = 200
p.e = 280
c = Canvas()
[Link] = 500
[Link] = 500
world = World()
draw_point(c,p)
[Link]()
Output:
Result: Thus, the python function to draw a representation of the Point on the
Canvas has been executed successfully.

35. Draws circles on the canvas.

Aim: To write a python function called draw_circle to define a new class called
Circle with appropriate attributes and instantiate a few Circle objects that draws
circles on the canvas.
Program:
from [Link] import *
class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
class Circle(object):
"""Represents a circle.
attributes: center point, radius"""
def draw_circle(canvas, circle):
drawn_canvas = [Link]([Link], [Link])
drawn_canvas.create_oval(circle.x, circle.x, circle.y, circle.y,
outline='darkgreen', fill='orange',width=5)
drawn_canvas.create_arc(circle.x, circle.x, circle.y, circle.y, start=0, extent=-
90,outline='brown', fill='olive',width=8)
c = Canvas()
[Link] = 500
[Link] = 500
c1 = Circle()
c1.x = 150
c1.y = 300
world = World()
draw_circle(c,c1)
[Link]()
Output:

Result: Thus, the python function called draw a circle on the canvas has been
executed successfully.
36. Method Resolution Order (MRO) in multiple levels of Inheritances.

Aim: To write a python program to demonstrate the usage of Method Resolution


Order (MRO) in multiple levels of Inheritances.
Program:
class A:
def method1(self):
print('class A method is called')
class B(A):
def method1(self):
print('class B method is called')
def method2(self):
print('class B method2 is called')
class C(A):
def method1(self):
print('class C method is called')
class D(C,B):
def display(self):
print('Class D method is called')
D.method1(self)
B.method1(self)
A.method1(self)
class E(B,C):
pass
d=D()
d.method1()
d.method2()
A.method1(d)
[Link]()
print("Displaying MRO order:")
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
Output:
Result: Thus, the python program to demonstrate the usage of Method Resolution
Order (MRO) in multiple levels of Inheritances has been executed successfully.

37. Validate phone number and email-id from the user

Aim: To write a python code to read a phone number and email-id from the user
and validate it for correctness.
Packages installation:
pip install re (type in command prompt)
pip install phonenumbers (type in command prompt)
Program:
import re
import phonenumbers
PhoneNo=input("Enter phone number along with country code: ")
Email=input("Enter email-id: ")
def isValidPhoneNo(input):
my_number=[Link](PhoneNo)
x=phonenumbers.is_valid_number(my_number)
y=phonenumbers.is_possible_number(my_number)
if x and y:
return (f"{input} is Correct Phone Number.")
return (f"{input} is Incorrect Phone Number.")
def isValidEmail(input):
pattern='^[a-z 0-9]+[\._]?[a-z 0-9]+[@]\w+[.]\w{2,3}$'
if [Link](pattern, input):
return (f"{input} is Correct Email.")
return (f"{input} is Incorrect Email.")
print("Entered Phone number is:",isValidPhoneNo(PhoneNo))
print("Entered Email-id is:",isValidEmail(Email))
Output:
Enter phone number along with country code: +919176260066
Enter email-id: abc12_34ef@[Link]
Entered Phone number is: +919176260066 is Correct Phone Number.
Entered Email-id is: abc12_34ef@[Link] is Correct Email.

Enter phone number along with country code: +919176260066


Enter email-id: _abc123@[Link]
Entered Phone number is: +919176260066 is Correct Phone Number.
Entered Email-id is: _abc123@[Link] is Incorrect Email.

Enter phone number along with country code: +9176260066


Enter email-id: mer,lin@[Link]
Entered Phone number is: +9176260066 is Incorrect Phone Number.
Entered Email-id is: abc,efg@[Link] is Incorrect Email.

Result: Thus, the python code to read a phone number and email-id from the
user and validated it for correctness has been executed successfully.

38. Install NumPy package with pip and explore it.

Aim: To install NumPy (Numerical Python) package with pip and explore it.

What is NumPy? It is an open-source library for the Python programming language.


It is used for scientific computing and working with arrays.
Why use NumPy?
 In Python - lists that serve the purpose of arrays, but they are slow to process.
 NumPy provide an array object that is faster than traditional Python lists.
 The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
 NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
Steps to install Numpy Package: (Do in command prompt)
1. Type cmd in search engine and click enter to open command prompt or type Run
in search engine then type cmd
2. Then check python is available in your system. For that type python --version or
python -V (If no python is available in your system, then install it by downloading
from online [Link] or through software)
3. Next check pip is in your system. For that type py -m pip --version
Note: PIP is a package manager for Python packages, or modules. It allows you to
install and manage packages that aren’t part of the Python standard library.
If pip is not available then type py -m pip install pip
4. Finally to install numpy package type py -m pip install numpy or
pip install numpy in command prompt
5. To check numpy is installed type pip list or pip show numpy
6. To upgrade numpy type pip install --upgrade numpy

To explore Numpy functionalities:


1. To check Numpy version and Import Numpy
To check Numpy version
To access NumPy and its functions import it in your Python code
Done by two ways
(i).

(ii).

2. Create and use Numpy arrays (NumPy ndarray Object) - array(), type()
To create an ndarray, we can pass a list, tuple or any array-like object into the
array() method, and it will be converted into an ndarray

zeros(): creating an array filled with 0’s


While the default data type is floating point (np.float64), you can explicitly specify
which data type you want using the dtype keyword.
ones(): array filled with 1’s
empty(): empty array. The function empty creates an array whose initial content is
random and depends on the state of the memory.
arrange(): create an array with a range of elements

3. Dimensions in array (ndim)


NumPy Arrays provides the ndim attribute that returns an integer that tells us how
many dimensions the array have.
[Link] will tell you the number of axes, or dimensions, of the array.
4. NumPy Array Indexing (Access Array Elements)
Array indexing is the same as accessing an array element. You can access an array
element by referring to its index number.
5. NumPy Array Slicing or Indexing

6. NumPy Data Types (Data Types in Python) - dtype()


7. Shape and size of an array
[Link] will display a tuple of integers that indicate the number of elements
stored along each dimension of the array.
[Link] will tell you the total number of elements of the array. This is the
product of the elements of the array’s shape.
8. Joining and Intersect NumPy Arrays
 Joining means putting contents of two or more arrays in a single array.
 We pass a sequence of arrays that we want to join to the concatenate()
function, along with the axis.

 Intersection means finding common values between two or more arrays


 Find the intersection of two arrays using intersect1d()

To return the indices of the values common to the input arrays along with the
intersected values:

9. NumPy Sorting Arrays


Sorting means putting elements in an ordered sequence.
Ordered sequence is any sequence that has an order corresponding to elements,
like numeric or alphabetical, ascending or descending.
The NumPy ndarray object has a function called sort(), that will sort a specified
array.
10. Numpy Math Array

Result: Thus, the python concepts to install NumPy (Numerical Python) package
with pip and through various functionalities has been explored successfully.

39. Import numpy, Plotpy (plotpy), Scipy and explore their functionalities

Aim: To import numpy, Plotpy and Scipy and explore their functionalities using
python
 NumPy- Numerical python (N-dimensional array package)
 SciPy- Scientific python (Fundamental library for scientific computing)
 Matplotlib- Comprehensive 2D Plotting
 NumPy is a general-purpose array-processing package.
 SciPy and NumPy are scientific projects whose aim is efficient and fast numeric
computing to Python.
 SciPy is a fully-featured version of Linear Algebra while NumPy contains only a
few features.
 NumPy is faster than other Python Libraries
 Matplotlib is the name of the python plotting library.
 Pyplot is an interactive API for matplotlib, like this: import [Link] as
plt.
To install package:
pip install scipy (type in command prompt)
pip install matplotlib (type in command prompt)
A. Working with Matplotlib
Matplotlib is a comprehensive library for creating interactive visualizations in
Python.
a. Plotting arrays with Matplotlib
Example-1:
import numpy as np
import [Link] as plt
a = [Link]([2, 1, 5, 7, 4, 6, 8, 14, 10, 9, 18, 20, 22])
[Link](a)
[Link]()
Output:

Example-2:
import numpy as np
import [Link] as plt
x = [Link](0, 5, 20)
y = [Link](0, 10, 20)
[Link](x, y, 'purple')
[Link](x, y, 'o')
[Link]()
Output:

b. Plotting using Matplotlib


Example:
from matplotlib import pyplot as plt
x = [5, 2, 9, 4, 7]
y = [10, 5, 8, 4, 2]
[Link](x,y)
[Link]()
Output:

B. Working with Scipy


Scipy is used to solve the complex scientific and mathematical problems. Numpy
and SciPy both are used for mathematical and numerical analysis. Numpy is
suitable for basic operations such as sorting, indexing and many more because it
contains array data, whereas SciPy consists of all the numeric data.
a. Using SciPy as Constant
The [Link] provides the mathematical constants.
Example:
#import scipy
import scipy as sp
#from [Link] import pi
print([Link])
#print([Link])

b. Using SciPy as Linear Algebra


A linear algebra problem can be solved by typing the following scipy function:
(i). Linear Equation: The [Link] is used to solve the linear equation
a*x + b*y = Z, for the unknown x, y values.
Example:
import numpy as np
from scipy import linalg
# Creating input array
a = [Link]([[1, 2], [2, 3]])
# Solution Array
b = [Link]([[7], [5]])
# Solve the linear algebra
x = [Link](a, b)
# Print results
print(x)
Output:

(ii). Find the determinants: The determinant of the square matrix is found by using
the [Link]() function.
Example:
from scipy import linalg
import numpy as np
#Declaring the numpy array
A = [Link]([[1,3],[-3,2]])
#Passing the values to the det function
x = [Link](A)
#printing the result
print(x)
Output:

Result: Thus the python concepts to import numpy, Plotpy and Scipy modules and
explore their functionalities using python has been executed successfully.
40. Implement Digital Logic Gates – AND, OR, NOT, EX-OR

Aim: To write a python program to implement Digital Logic Gates – AND, OR,
NOT, EX-OR.

Program:
def AND(A,B):
#return (A & B)
if A == 1 and B == 1:
return bool(1)
else:
return bool(0)
def OR(A,B):
#return (A | B)
if A == 1:
return True
elif B == 1:
return True
else:
return False
def NOT(A):
#return (~A+2)
if(A == 0):
return True
elif(A == 1):
return False
def XOR(A,B):
#return (A^B)
if A != B:
return bool(True)
else:
return bool(False)
print("--------AND Gate---------")
print("0 AND 0 is", AND(0, 0))
print("0 AND 1 is", AND(0, 1))
print("1 AND 0 is", AND(1, 0))
print("1 AND 1 is", AND(1, 1))
print("--------OR Gate----------")
print("0 OR 0 is", OR(0, 0))
print("0 OR 1 is", OR(0, 1))
print("1 OR 0 is", OR(1, 0))
print("1 OR 1 is", OR(1, 1))
print("--------NOT Gate---------")
print("NOT 0 is", NOT(0))
print("NOT 1 is", NOT(1))
print("--------XOR Gate---------")
print("0 XOR 0 is", XOR(0, 0))
print("0 XOR 1 is", XOR(0, 1))
print("1 XOR 0 is", XOR(1, 0))
print("1 XOR 1 is", XOR(1, 1))
Output:

Result: Thus the python program to implement Digital Logic Gates – AND, OR,
NOT, EX-OR has been executed successfully.

41. Implement Half Adder, Full Adder, and Parallel Adder

Aim: To write a python program to implement Half Adder, Full Adder, and Parallel
Adder
A. Half Adder:
Program:
import numpy as np
def half_adder(a, b):
Sum = np.bitwise_xor(a, b)
Carry = np.bitwise_and(a, b)
return Sum, Carry
print("a, b sum, carry")
print("- - --- -----")
print("0, 0 ",half_adder(0, 0))
print("0, 1 ",half_adder(0, 1))
print("1, 0 ",half_adder(1, 0))
print("1, 1 ",half_adder(1, 1))
print("----------------")
Output:

B. Full Adder:
Program: (using two half adders)
def half_adder(a, b):
# &, ^ is logical and, xor in python
sum = a ^ b
carry = a and b
return carry, sum
def full_adder(a, b, carry_in):
carry1,sum1 = half_adder(carry_in,a)
carry2,sum2 = half_adder(sum1,b)
carry = carry1 or carry2
return sum2, carry
print("a, b cin| sum,cout")
print("- - - | --- ---")
print("0, 0, 0 |",full_adder(0, 0, 0))
print("0, 0, 1 |",full_adder(0, 0, 1))
print("0, 1, 0 |",full_adder(0, 1, 0))
print("0, 1, 1 |",full_adder(0, 1, 1))
print("1, 0, 0 |",full_adder(1, 0, 0))
print("1, 0, 1 |",full_adder(1, 0, 1))
print("1, 1, 0 |",full_adder(1, 1, 0))
print("1, 1, 1 |",full_adder(1, 1, 1))
print("-------------------")
Output:

C. Parallel Adder: (4-bit parallel adder)


Program:
def half_adder(a, b):
# &, ^ is logical and, xor in python
Sum = a ^ b
Carry = a and b
return Carry,Sum
def full_adder(a, b, carry_in):
carry1,sum1 = half_adder(carry_in,a)
carry2,sum2 = half_adder(sum1,b)
carry = carry1 or carry2
return sum2, carry
def parallel_adder(A,B,cin):
c3=0
s0, c0=full_adder(A[3],B[3],cin)
s1, c1=full_adder(A[2],B[2],c0)
s2, c2=full_adder(A[1],B[1],c1)
s3, c3=full_adder(A[0],B[0],c2)
print("sum=",s3,s2,s1,s0)
print("carry=",c3)
return
#A=(0,1,0,1) #5
#B=(1,0,1,0) #10
A=(1,0,1,1) #11
B=(1,0,1,1) #11
print("Parallel Adder for input")
print("A=(1,0,1,1),B=(1,0,1,1) is")
parallel_adder(A,B,0)
Output:

Result: Thus, the python program to implement Half Adder, Full Adder, and Parallel
Adder has been executed successfully.

42. GUI python program to create a window wizard

Aim: To write a GUI python program to create a window wizard having two text
labels, two text fields and two buttons as Submit and Reset.
To install package: pip install tk
Program:
import tkinter
window=[Link]()
[Link]('GUI program to create a window wizard')
[Link]("250x240")
#Creating widgets
text_label1=[Link](window,text="Username")
text_label2=[Link](window,text="Password")
text_field1=[Link](window)
text_field2=[Link](window,show="*")
button1=[Link](window,text="Submit")
button2=[Link](window,text="Reset")
#Placing widgets on the screen
text_label1.grid(row=1,column=0)
text_label2.grid(row=2,column=0)
text_field1.grid(row=1,column=1)
text_field2.grid(row=2,column=1)
[Link](row=3,column=0)
[Link](row=3,column=1)
[Link]()
[Link]()

Output:

Result: Thus, the GUI python program to create a window wizard having two text
labels, two text fields and two buttons as Submit and Reset has been executed
successfully.

You might also like