0% found this document useful (0 votes)
12 views28 pages

Wa0002.

The document contains practical programming exercises in Python covering various topics such as creating a simple calculator, solving quadratic equations, calculating customer fares, performing list operations, computing net run rates, and checking character types. It also includes data visualization techniques using matplotlib for different plots like line, bar, histogram, scatter, and pie charts, along with statistical calculations for mean, mode, and median. Additionally, it demonstrates the creation of 2D arrays using NumPy and converting Python lists to NumPy arrays.

Uploaded by

garenafflegendpc
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)
12 views28 pages

Wa0002.

The document contains practical programming exercises in Python covering various topics such as creating a simple calculator, solving quadratic equations, calculating customer fares, performing list operations, computing net run rates, and checking character types. It also includes data visualization techniques using matplotlib for different plots like line, bar, histogram, scatter, and pie charts, along with statistical calculations for mean, mode, and median. Additionally, it demonstrates the creation of 2D arrays using NumPy and converting Python lists to NumPy arrays.

Uploaded by

garenafflegendpc
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
You are on page 1/ 28

Practical No.

1
Aim - Write a program to make a simple calculator

Source Code -
# This function adds two numbers
def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
178
print("Invalid input. Please enter a number.")
continue

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")

Output -

179
Practical No 2
AIM- Write a python program which can solve a quadratic equation.
Formula: Let ax2 + bx + c = 0 is a quadratic equation where a, b and c are real
and a ≠ 0,then Quadratic formula is

SOURCE CODE-
import math

# Function for finding roots


def equationroots(a, b, c):
# Calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))

# Checking condition for discriminant


if dis > 0:
print("Real and different roots")
print((-b + sqrt_val) / (2 * a))
print((-b - sqrt_val) / (2 * a))
elif dis == 0:
print("Real and same roots")
print(-b / (2 * a))
else:
print("Complex Roots")
print(-b / (2 * a), "+", sqrt_val, "i")
print(-b / (2 * a), "-", sqrt_val, "i")

# Driver Program
a = int(input('Enter the value of a = '))
b = int(input('Enter the value of b = '))
c = int(input('Enter the value of c = '))
# If a is 0, then incorrect equation
if a == 0:
print("Input correct quadratic equation")
else:
equationroots(a, b, c)

180
OUTPUT-
For a quadratic equation with real and different roots:
Enter the value of a = 1
Enter the value of b = -7
Enter the value of c = 10
Real and different roots
5.0
2.0

For a quadratic equation with real and same roots:


Enter the value of a = 1
Enter the value of b = -6
Enter the value of c = 9
Real and same roots
3.0

181
Practical No - 3
AIM- A tours and travels company charges their customer as per following criteria according
to customer category.
Category Charges

A 18

B 15

C 12

D 10

Others 20

SOURCE CODE-
def cust_fare():
ctype = input('Enter Customer Type: ')
try:
dist = int(input('Enter distance = '))
except ValueError:
print("Invalid input for distance. Please enter a valid integer.")
return

if ctype == 'A':
ch = 18
elif ctype == 'B':
ch = 15
elif ctype == 'C':
ch = 12
elif ctype == 'D':
ch = 10
else:
ch = 20

fare = dist * ch
print('Total Amount = ', fare * 2)

cust_fare()

182
OUTPUT-

Enter Customer Type: A

Enter distance = 10

Total Amount = 360

183
Practical No - 4
Lists & its Operations

AIM- Write a Python program:-


1. To declare a list as num = [10, 30, 40, 20, 50] and print it.
2. To sort the list num in Ascending and the Descending order in Python.
3. To create a list as List1 = ['Hello', 10, 'world', 20] and iterate in reverse order.
4. To remove an element of List1 using List1.pop() .
5. To add an element to a List1 using List1.append().

SOURCE CODE-
# 1. List of integers
num = [10, 30, 40, 20, 50]
print("The num list :", num)

# 2. Sort the list num in Ascending order


num.sort()
print("The list num in Ascending order: ", num)

# Sort the list num in Descending order


num.sort(reverse=True)
print("The list num in descending order: ", num)

# 3. Create list List1 and reverse


List1 = ['Hello', 10, 'world', 20]
print("The List1 :-", List1)

# Reverse the list


List1 = List1[::-1]
# Print the list
print("List1 in reverse order: ", List1)

# 4. Removing elements
List1.pop()
# Printing list after removing
print("List elements after removing from List1: ", List1)

# 5. Adding elements to List1


List1.append(50)
List1.append("Chennai")

184
# Printing list after adding
print("List elements after adding to List1: ", List1)

OUTPUT -
The num list : [10, 30, 40, 20, 50]
The list num in Ascending order: [10, 20, 30, 40, 50]
The list num in descending order: [50, 40, 30, 20, 10]
The List1 :- ['Hello', 10, 'world', 20]
List1 in reverse order: [20, 'world', 10, 'Hello']
List elements after removing from List1: [20, 'world', 10]
List elements after adding to List1: [20, 'world', 10, 50, 'Chennai']

185
Practical No 5

Aim : Write a program to compute the net run rate for a tournament.

Source Code -
#Enter details for team, for and against data
tn = input("Enter Team name:")
n = int(input("Enter no. of matches played:"))

# Variables to store total scores and overs


tr = 0
to = 0
tagr = 0
togr = 0

# Entering runs and overs and adding them for n number of matches
for i in range(n):
r = int(input("Enter runs scored in match " + str(i + 1) + ": "))
o = int(input("Enter overs played: "))
tr = r + tr
to = to + o
agr = int(input("Enter runs conceded in match " + str(i + 1) + ": "))
ogr = int(input("Enter overs bowled: "))
tagr += agr
togr += ogr

# Computing the net runrate


nrr = (tr / to) - (tagr / togr)

# Displaying the net runrate


print("Net runrate is:", nrr)

Output -
Practical No 6

Aim - Write a program to check whether the given character is an uppercase letter or
lowercase letter or a digit or a special character.

Source Code -
#Input the character to check
ch = input("Enter Any Character:")
# Checking whether it is an uppercase letter, lowercase letter, digit, space, or a special
character
if ch.isupper():
print(ch, "is an upper case letter")
elif ch.islower():
print(ch, "is a lower case letter")
elif ch.isdigit():
print(ch, "is a digit")
elif ch.isspace():
print(ch, "is a space")
else:
print(ch, "is a special character")

Output -
Practical No - 7
Aim - Write a program to find the maximum number out of the given three numbers.

Source Code -
# Take input of three numbers to compare
n1 = int(input("Enter Number 1: "))
n2 = int(input("Enter Number 2: "))
n3 = int(input("Enter Number 3: "))

if n1 > n2 and n1 > n3:


print(n1, "- Number 1 is greater")
elif n2 > n1 and n2 > n3:
print(n2, "- Number 2 is greater")
elif n3 > n1 and n3 > n2:
print(n3, "- Number 3 is greater")
else:
print("All are the same or some are equal")

Output -
Practical No - 8
Aim - Write a program to check whether the entered number is Armstrong or not.

Source Code -
# Enter a number to check
n = int(input("Enter number to check: "))

# Store the original number into a temporary variable


t=n
s=0

# Computing the sum of the cube of each digit and iterating until n = 0
while n != 0:
r = n % 10
s = s + (r**3)
n //= 10

# Checking & displaying whether Armstrong or not


if t == s:
print(t, "is an Armstrong number")
else:
print(t, "is not an Armstrong number")

Output -
Practical No. 9
Aim - Write a short note about five essential plots that can help in data visualization &
write a python program to show each.
Introduction: Data visualization is the process of turning your data into
graphical representations that communicate logical relationships and lead to
more informed
decision-making.In short, data visualization is the representation of data in a
graphical or pictorial format.
There are five essential plots that have we need to know well for basic data
visualization.
 Line Plot
 Bar Chart
 Histogram Plot
 Scatter Plot
 Pie Chart
1. Line Plot:
• A line plot is used to show observations gathered at regular intervals.
• The x-axis shows the regular interval, such as time.
• The Y- axis shows the observations.
• A line plot can be built by the calling the plot() function and
passing the X- axis data for the regular interval, and Y – axis for
the observations.
# code to create a line plot
pyplot.plot(x, y)
2. Bar Plot:
 A bar chart presents relative quantities for multiple categories.
 The x-axis shows the categories that are spaced evenly.
 The Y- axis shows the quantity for each category and is drawn as a bar from the
baseline to the required level on the Y-axis.
 A bar chart can be built by the calling the bar() function and passing the category
names for the X-axis and the quantities for the Y – axis.
3. Histogram Plot
 Histogram plots are used for summarizing the distribution of a data sample.
 The x-axis shows distinct bins or intervals for the observation.
 The Y- axis shows the frequency or tally of the number of
observations in the dataset that has assigned to each bin.
 A Histogram plot can be designed by the calling the hist()
function and passing a list or array that shows the data
sample.
# code to create a histogram plot
pyplot.hist(x, y)
4. Scatter Plot:
 A scatter plot can be designed by the calling the scatter() function and passing
a list or array that shows the data sample.
# code to create a scatter plot
pyplot. Scatter(x, y)
5. Pie Chart
 A Pie Chart is a circular statistical plot that can display only one series of
data.
 The area of the chart is the total percentage of the given data. The area of
slices of the pie represents the percentage of the parts of the data
 # code to create a pie plot
pyplot.pie(values, labels =
Names)

Source Code -
# importing the required libraries
import matplotlib.pyplot as plt
import numpy as np

# define data values


x = np.array([1, 2, 3, 4]) # X-axis points
y = x * 2 # Y-axis points

plt.plot(x, y) # Plot the chart


plt.show() # display

# creating the dataset


data = {'C': 20, 'C++': 15, 'Java': 30, 'Python': 35}
courses = list(data.keys())
values = list(data.values())

fig = plt.figure(figsize=(10, 5))

# creating the bar plot


plt.bar(courses, values, color='maroon', width=0.4)
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()

# Creating dataset
a = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27])

# Creating histogram
fig, ax = plt.subplots(figsize=(10, 7))
ax.hist(a, bins=[0, 25, 50, 75, 100])
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Histogram of a")
plt.show()

x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]


y = [99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86]

plt.scatter(x, y, c="blue")

# To show the plot


plt.show()

values = [12, 45, 60, 46, 78]


necessity = ['food', 'rent', 'shopping', 'entertainment', 'others']
plt.pie(values, labels=necessity)
plt.show()
Output -
Practical No. 10
Aim - Write a menu-driven program to calculate the mean, mode and median for
the given data:
[5,6,1,3,4,5,6,2,7,8,6,5,4,6,5,1,2,3,4]

Source Code :
import statistics
# Creating list
l = [5, 6, 1, 3, 4, 5, 6, 2, 7, 8, 6, 5, 4, 6, 5, 1, 2, 3, 4]
# Display mean, mode, and median value using functions
print("Mean Value: %.2f" % statistics.mean(l))
try:
print("Mode Value: %.2f" % statistics.mode(l))
except statistics.StatisticsError:
print("Multiple modes exist.")
print("Median Value: %.2f" % statistics.median(l))

Output -
Practical No 11

Aim - Write a program to create a 2D array using NumPy.

Source Code -

#import numpy package


import numpy as np

# Creating array using arange() function


arr = np.arange(5, 45, 5)

# Reshaping array for 2D


arr = arr.reshape(4, 2)

# Printing array
print(arr)

Output -
[[ 5 10]
[15 20]
[25 30]
[35 40]]
Practical No. 12

Aim - Write a program to convert a python list to a NumPy array.

Source Code -
# Import NumPy Package
import numpy as np

# Creating empty list


l = []

# Take input for n no. of elements


n = int(input("Enter the number of elements:"))

# Append the values into the list


for i in range(n):
val = int(input("Enter value " + str(i+1) + ":"))
l.append(val)

# Converting list into numpy array


arr = np.array(l)

print("Array:", arr)

Output -
Practical No : 13 Computer Vision

1. Visit this link (https://www.w3schools.com/colors/colors_rgb.asp). On the basis of


this online tool, try and write answers of all the below-mentioned questions.
o What is the output colour when you put R=G=B=255?
o What is the output colour when you put R=G=255,B=0?
o What is the output colour when you put R=255,G=0,B=255?
o What is the output colour when you put R=0,G=255,B=255?
o What is the output colour when you put R=G=B=0?
o What is the output colour when you Put R=0,G=0,B=255?
o What is the output colour when you Put R=255,G=0,B=0?
o What is the output colour when you put R=0,G=255,B=0?
o What is the value of your colour?

Solution:

1. White
2. Yellow
3. Pink
4. Cyan
5. Black
6. Blue
7. Red
8. Green
9. R=0,G=0,B=255

2. Create your own pixels on piskelapp (https://www.piskelapp.com/) and make a


gif image.

Steps:
1. Open piskelapp on your browser.
2. Apply background for the picture.
3. Use pen to draw letter A
4. Copy the layer and paste it
5. Now erase letter A written previously
6. Apply the background colour for layer 2
7. Change the pen colour and Write I
8. Export the image.
9. Follow this link to access animated GIF: Click here

3. Do the following tasks in OpenCV.


a. Load an image and Give the title of the image
b. Change the colour of image and Change the image to grayscale
c. Print the shape of image
d. Display the maximum and minimum pixels of image
e. Crop the image and extract the part of an image
f. Save the Image
1. Load Image and Give the title of image

#import required module cv2, matplotlib and numpy

import cv2

import matplotlib.pyplot as plt

import numpy as np

#Load the image file into memory

img = cv2.imread('octopus.png')

#Display Image

plt.imshow(img)

plt.title('Octopus')

plt.axis('off')

plt.show()

2. Change the colour of image and Change the image to grayscale


#import required module cv2, matplotlib and numpy
import cv2
import matplotlib.pyplot as plt
import numpy as np
#Load the image file into memory
img = cv2.imread('octopus.png')
#Chaning image colour image colour
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('Octopus')
plt.axis('off')
plt.show()
3. Print the shape of image
import cv2
img = cv2.imread('octopus.png',0)
(1920, 1357)
print(img.shape)
4. Display the maximum and minimum pixels of image
import cv2
img = cv2.imread('octopus.png',0)
print(img.min()) 0
255
print(img.max())
5. Crop the image and extract the part of an image
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('octopus.png')
pi=img[150:400,100:200]
plt.imshow(cv2.cvtColor(pi, cv2.COLOR_BGR2RGB))
plt.title('Octopus')
plt.axis('off')
plt.show()
6. Save the Image
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('octopus.png')
plt.imshow(img)
cv2.imwrite('oct.jpg',img)
plt.title('Octopus')
plt.axis('off')
plt.show()
Practical No - 14
Introduction to Computer Vision

AIM- Write a Python program


a. To read and display an image using OpenCV in Google Colab.
b. To display the height and width of an input image.
c. To covert BGR format of OpenCV to RGB format.

Introduction:

Computer Vision Computer vision is a field/domain of artificial intelligence (AI) that


enables computers and systems to derive meaningful information from digital images,
videos and other visual inputs — and take actions or make recommendations based on
that information.
OpenCV-Python is a library of Python bindings designed to solve computer vision
problems. Python is a general purpose programming language started by Guido van
Rossum that became very popular very quickly, mainly because of its simplicity and
code readability. It enables the programmer to express ideas in fewer lines of code
without reducing readability. OpenCV was started at Intel in 1999 by Gary Bradsky, and
the first release came out in 2000. Vadim Pisarevsky joined Gary Bradsky to manage
Intel's Russian software OpenCV team. In 2005, OpenCV was used on Stanley, the
vehicle that won the 2005 DARPA Grand Challenge.
SOURCE CODE-
# Importing the OpenCV library
import cv2
# Importing the matplotlib library
import matplotlib.pyplot as plt

# Reading the image using imread() function


image = cv2.imread('/road.jpg')
# Displaying the image using imshow() function
plt.imshow(image)

# Extracting the height and width of an image


h, w = image.shape[:2]
# Displaying the height and width
print("Height = {}, Width = {}".format(h, w))

# Converting the image to RGB format using cvtColor() function


imgrgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(imgrgb),plt.title("RGB FROMAT of given Image")
# Extracting the height and width of an image
h, w = imgrgb.shape[:2]
# Displaying the height and width
print("Height = {}, Width = {}".format(h, w))
188
OUTPUT-

RESULT- The source code is executed successfully and the output was verified.

189
Practical No. - 15
Common Image Manipulation Using OpenCV
AIM- Write a Python program
a. To resize the image using resize().
b. To display the region of interest of an image.
c. To rotate an image.

SOURCE CODE-
# Importing the OpenCV library
import cv2
# Importing the matplotlib library
import matplotlib.pyplot as plt

# Reading the image using imread() function


image = cv2.imread('/road.jpg')
# Displaying the image using imshow() function
plt.imshow(image),plt.title(“ORIGINAL IMAGE”)

# Extracting the height and width of an image


h, w = image.shape[:2]
# Displaying the height and width
print("Height = {}, Width = {}".format(h, w))

# resize() function takes 2 parameters,


# the image and the dimensions
resize = cv2.resize(image, (800, 800))
plt.imshow(resize),plt.title(“RESIZED IMAGE”)

# We will calculate the region of interest


# by slicing the pixels of the image
roi = image[100 : 500, 200 : 700]
plt.imshow(roi),plt.title("REGION OF INTEREST IMAGE")

# Calculating the center of the image


center = (w // 2, h // 2)

# Generating a rotation matrix


matrix = cv2.getRotationMatrix2D(center, -45, 1.0)

# Performing the affine transformation


rotated = cv2.warpAffine(image, matrix, (w, h))
plt.imshow(rotated),plt.title("ROTATED IMAGE")

190
OUTPUT-

You might also like