Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

Experiment No.

Theory:
Python data types are classes and variables are instances (objects) of these classes. The
following are the standard or built-in data types in Python:
Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric
value can be an integer, a floating number, or even a complex number.
Sequence Data Type in Python

String Data Type - Strings in Python are arrays of bytes representing Unicode characters.
A string is a collection of one or more characters put in a single quote, double-quote, or
triple-quote.

List Data Type - Lists are just like arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of the same type.

Tuple Data Type - Just like a list, a tuple is also an ordered collection of Python objects.
The only difference between a tuple and a list is that tuples are immutable i.e. tuples cannot
be modified after it is created. It is represented by a tuple class.

Boolean Data Type in Python


Python Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false).

Set Data Type - In Python Data Types, a Set is an unordered collection of data types that is
iterable, mutable, and has no duplicate elements. The order of elements in a set is undefined
though it may consist of various elements.

Dictionary Data Type in Python


A dictionary in Python is an unordered collection of data values, a Dictionary holds a key:
value pair. Key-value is provided in the dictionary to make it more optimized. Each key-
value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.

Aim:- Write a program to carry out the following operations on the given set
s = {10, 2, -3, 4, 5, 88}
a. Number of items in sets s
b. Maximum element in sets s
c. Minimum element in sets s
d. Sum of all elements in sets s
e. Obtain a new sorted set from s, set s remaining unchanged
f. Report whether 100 is an element of sets s
g. Report whether -3 is not an element of sets s.

Program:
s = {10, 2, -3, 4, 5, 88}
num_items = len(s)
print("number of items is set: ", num_items)

max_items = max(s)
print("max number of items is set: ", max_items)

min_items = min(s)
print("min number of items is set: ", min_items)

sum_items = sum(s)
print("sum number of items is set: ", sum_items)

sort = sorted(s)
print("sorted items in set: ", sort)

if 100 in s:
print("is element of s")
else:
print("is not element of s")

if -3 not in s:
print("is not element of s")
else:
print("is element of s")

Output:

Experiment No. 2

Theory:
Sometimes the programmer needs to check the evaluation of certain
expression(s), whether the expression(s) evaluate to True or False. If the
expression evaluates to False, then the program execution follows a different
path than it would have if the expression had evaluated to True.
Based on this, the conditional statements are further classified into following
types:
● if
● if-else
● if-else-elif
● nested if-else-elif.

Sometimes a programmer wants to execute a group of statements a certain


number of times. This can be done using loops. Based on this loops are
further classified into following main types;
● for loop
● while loop

Aim :- Write Python program to implement control structures.

a. Program to check if number is positive or negative. (using conditional


statements)
Code:
number = int(input("enter a number"))
if number > 0:
print(f"{number} is a positive number.")
elif number < 0:
print(f"{number} is a negative number.")
else:
print(f"{number} is zero.")

Output:

b. Program to print numbers upto specified range.(using loops)


Code:

n = int(input("Enter a number: "))

print("Numbers up to", n, ":")


for i in range(1, n + 1):
print(i, "\n")

Output:

Experiment No. 3
Theory:
Python Functions is a block of statements that return the specific task. The idea is to put
some commonly or repeatedly done tasks together and make a function so that instead
of writing the same code again and again for different inputs, we can do the function
calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
● Increase Code Readability
● Increase Code Reusability

Python Function Declaration


The syntax to declare a function is:

Types of Functions in Python

There are mainly two types of functions in Python.


● Built-in library function: These are Standard functions in Python that are
available to use.
● User-defined function: We can create our own functions based on our
requirements.

Aim :- Write a Python function that accepts a string and counts the number of upper
and lower case letters.

Program:
sen = input("Enter a string")
def check(s):

d = {'Uppercase':0, 'Lowercase':0}
for c in s:
if c.isupper():
d['Uppercase'] += 1

elif c.islower():
d['Lowercase'] += 1

else:
d['Lowercase'] += 0
d['Uppercase'] += 0

print("Original string: ",s)

print("Uppercase characters: ", d['Uppercase'])

print("Lowercase characters: ", d['Lowercase'])

check(sen)

Output:

Experiment No. 4
Python File Handling
Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
Python File Open
Before performing any operation on the file like reading or writing, first, we have to open that file.
For this, we should use Python’s inbuilt function open() but at the time of opening, we have to
specify the mode, which represents the purpose of the opening file.
Where the following mode is supported:

1. r: open an existing file for a read operation.


2. w: open an existing file for a write operation. If the file already contains some data, then it
will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.

Program :- Write python program to understand different File handling operations

1. Write a Python program to read an entire text file.

f = open("file2.txt" , 'r')
content = f.readlines()
print(content)

Output:
2. Write a Python program to append text to a file and display the text.

f = open("file2.txt" , 'a')
f.write("This is appended text")
f.close()

Output:

3. WRite a Python program to create a new directory named “dir1” , create a


new text file with name “file1” , write some content in “file1” and read contents
of “file1”

import os

os.mkdir("dir1")

with open("file2.txt", 'x') as f:


f.write("This is new file")

with open("file2.txt", 'r') as c:


txt = c.read()
print(txt)

Output:
Experiment No. 5
Theory:

The basic idea of object-oriented programming (OOP) in Python is to use classes and objects to
represent real-world concepts and entities.

A class is a blueprint or template for creating objects. It defines the properties and methods that an
object of that class will have. Properties are the data or state of an object, and methods are the actions
or behaviors that an object can perform.

An object is an instance of a class, and it contains its own data and methods. For example, you could
create a class called "Person" that has properties such as name and age, and methods such as speak()
and walk(). Each instance of the Person class would be a unique object with its own name and age,
but they would all have the same methods to speak and walk.
One of the key features of OOP in Python is encapsulation, which means that the internal state of
an object is hidden and can only be accessed or modified through the object's methods. This helps to
protect the object's data and prevent it from being modified in unexpected ways.

Another key feature of OOP in Python is inheritance, which allows new classes to be created that
inherit the properties and methods of an existing class. This allows for code reuse and makes it easy
to create new classes that have similar functionality to existing classes.

Polymorphism is also supported in Python, which means that objects of different classes can be
treated as if they were objects of a common class. This allows for greater flexibility in code and
makes it easier to write code that can work with multiple types of objects.

Aim :- Write a Python program to create a calculator class. Include methods for basic
arithmetic operations.

Program:

class Calculator:

def add(self, x, y):


return x + y

def subtract(self, x, y):


return x - y

def multiply(self, x, y):


return x * y

def divide(self, x, y):


if y != 0:
return x / y
else:
return ("Cannot divide by zero.")

calculator = Calculator()

result = calculator.add(7, 5)
print("7 + 5 =", result)

result = calculator.subtract(34, 21)


print("34 - 21 =", result)

result = calculator.multiply(54, 2)
print("54 * 2 =", result)

result = calculator.divide(144, 2)
print("144 / 2 =", result)

result = calculator.divide(45, 0)
print("45 / 0 =", result)

Output:

Experiment No. 6
Theory:

Python Class and Objects

A class is a blueprint or a template for creating objects, providing initial values for state (member
variables or attributes), and implementations of behaviour (member functions or methods). The user-
defined objects are created using the class keyword.

Creating a Class:

Let us now create a class using the class keyword.

class Details:

name = "Rohan"
age = 20

Creating an Object:

Object is the instance of the class used to access the properties of the class Now lets create an object
of the class.

Example:

obj1 = Details()

Aim :- Using OOPS write a python program for following: If ages of Ram, Shyam, and
Ajay are given as an input through the keyboard, write a program to determine the
youngest of the three.

Program:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

class Youngest:
def __init__(self):
self.people = []

def add_person(self, name, age):


person = Person(name, age)
self.people.append(person)
def find_youngest(self):
youngest_person = min(self.people, key=lambda x: x.age)
return youngest_person.name

if __name__ == "__main__":
youngest_detector = Youngest()
for i in range(3):
name = input("Enter name: ")
age = int(input("Enter age: "))
youngest_detector.add_person(name, age)

youngest_name = youngest_detector.find_youngest()
print(f"The youngest person is: {youngest_name}")

Output:

Experiment No. 7

Theory:

Python GUI – tkinter

Out of all the GUI methods, tkinter is the most commonly used method. It is a

standard Python interface to the Tk GUI toolkit shipped with Python. Python tkinter is

the fastest and easiest way to create GUI applications. Creating a GUI using tkinter

is an easy task.
To create a tkinter Python app:

1. Importing the module – tkinter


2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.

Importing a tkinter is the same as importing any other module in the Python code.
Note that the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is
‘tkinter’.

import tkinter

Aim :- Write Python program to implement GUI Canvas application using Tkinter.

Program:
import tkinter as tk

class CanvasApp:
def __init__(self, master):
self.master = master
self.master.title("Canvas Application")

self.canvas = tk.Canvas(self.master, width=400, height=400, bg="white")


self.canvas.pack()

self.canvas.bind("<B1-Motion>", self.draw)

def draw(self, event):


x1, y1 = (event.x - 5), (event.y - 5)
x2, y2 = (event.x + 5), (event.y + 5)
self.canvas.create_oval(x1, y1, x2, y2, fill="black")

def main():
root = tk.Tk()
app = CanvasApp(root)
root.mainloop()

if __name__ == "__main__":
main()

Output:

Experiment No. 8
OpenCV in Python

OpenCV, short for Open Source Computer Vision Library, is an open-source


computer vision and machine learning software library. Originally developed by Intel,
it is now maintained by a community of developers under the OpenCV Foundation.
OpenCV is a huge open-source library for computer vision, machine learning, and
image processing.It can process images and videos to identify objects, faces, or
even the handwriting of a human. When it is integrated with various libraries, such as
Numpy which is a highly optimized library for numerical operations, then the number
of weapons increases in your Arsenal i.e whatever operations one can do in Numpy
can be combined with OpenCV.

OpenCV Python Program to analyze an image using Histogram


In this article, image analysis using Matplotlib and OpenCV is discussed. Let’s first
understand how to experiment image data with various styles and how to represent
with Histogram.
Prerequisites:
● OpenCV
● matplotlib

Importing image data

import matplotlib.pyplot as plt #importing matplotlib

In Matplotlib, this is performed using the imshow() function. Here we have grabbed the plot
object.

Aim :- Write Python program to obtain histogram of any image

Program:
import cv2
from matplotlib import pyplot as plt
import numpy as np

img = cv2.imread('wp.jpg')

def plot_histogram(img, title, mask=None):


channels = cv2.split(img)
colors = ("b", "g", "r")
plt.title(title)
plt.xlabel("Bins")
plt.ylabel("# of Pixels")

for (channel, color) in zip(channels, colors):


hist = cv2.calcHist([channel], [0], mask, [256], [0, 256])
plt.plot(hist, color=color)
plt.xlim([0, 256])

mask = np.zeros(img.shape[:2], dtype="uint8")


cv2.rectangle(mask, (160, 130), (410, 290), 255, -1)

masked = cv2.bitwise_and(img, img, mask=mask)

plot_histogram(img, "Histogram for Masked Image", mask=mask)

plt.show()
cv2.imshow("Mask", mask)
cv2.imshow("Mask Image", masked)
cv2.waitKey(0)

Output:

Experiment No. 9

Theory:

Data Analysis with SciPy

Scipy is a Python library useful for solving many mathematical equations and
algorithms. It is designed on the top of Numpy library that gives more extension of
finding scientific mathematical formulae like Matrix Rank, Inverse, polynomial
equations, LU Decomposition, etc.

How does Data Analysis work with SciPy?


Data Preparation

● Import the necessary libraries: import numpy as np and import scipy as sp.
● Load or generate your dataset using NumPy or pandas.

Exploratory Data Analysis (EDA)

● Use descriptive statistics from SciPy’s stats module to gain insights into the
dataset.
● Calculate measures such as mean, median, standard deviation, skewness, kurtosis,
etc.

Regression Analysis

Utilize the linregress function for linear regression analysis.


# Linear regression

slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)

Aim :- Write python program to use SciPy to solve a linear algebra problem

Program:
import numpy as np
from scipy.linalg import solve

# Coefficients of the linear equations


A = np.array([[2, 1], [1, -1]])
b = np.array([5, 1])

# Solve the linear equations


solution = solve(A, b)

# Print the solution


print("Solution for x and y:", solution)

Output:
Experiment No. 10

Aim :- Analyze the “auto mpg data” and draw a pair plot using seaborn library for
mpg, weight, and origin. (a) Origin: This dataset was taken from the StatLib library
maintained at Carnegie Mellon University. Number of Instances: 398 Number of
Attributes: 9 including the class attribute Attribute Information: mpg: continuous
cylinders: multi-valued discrete displacement: continuous horsepower: continuous
weight: continuous acceleration: continuous model year: multi-valued discrete
origin: multi-valued discrete car name: string (unique for each instance)

Program:
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# Load the dataset


auto_mpg_data_url =
"https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight',
'acceleration', 'model_year', 'origin', 'car_name']
auto_mpg_df = pd.read_csv(auto_mpg_data_url, delim_whitespace=True,
names=column_names)

# Select required columns


selected_columns = ['mpg', 'weight', 'origin']
selected_data = auto_mpg_df[selected_columns]

# Draw pair plot


sns.pairplot(selected_data, hue='origin', markers=["o", "s", "D"])
plt.title('Pair Plot of MPG, Weight, and Origin')
plt.show()

Output:

Experiment No. 11

Aim :- Write Python Program to study image morphological operations

Program:
import cv2
import numpy as np
from matplotlib import pyplot as plt

# Read the image


image = cv2.imread('wp.jpg', cv2.IMREAD_GRAYSCALE)

# Perform morphological operations


kernel = np.ones((5, 5), np.uint8)

# Erosion
erosion = cv2.erode(image, kernel, iterations=1)
# Dilation
dilation = cv2.dilate(image, kernel, iterations=1)

# Opening
opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)

# Closing
closing = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)

# Plot the images


titles = ['Original', 'Erosion', 'Dilation', 'Opening', 'Closing']
images = [image, erosion, dilation, opening, closing]

for i in range(len(images)):
plt.subplot(2, 3, i+1)
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])

plt.show()

Output:
Experiment No. 12
Aim :- Write python program to study logistic regression
Program:
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report

# Load the Iris dataset


iris = load_iris()
X = iris.data
y = iris.target

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

# Initialize the Logistic Regression model


model = LogisticRegression(max_iter=1000)

# Train the model on the training set


model.fit(X_train, y_train)

# Make predictions on the testing set


y_pred = model.predict(X_test)

# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

# Print classification report


print("\nClassification Report:")
print(classification_report(y_test, y_pred))

Output:
Case Study 1
Solving a linear differential equation using SciKit and plotting the result in matplotlib. Students can
use differential equations from any previous topic studied in the programme such as mechanics,
materials science, fluid mechanics, kinematics of machines, thermodynamics, production etc.

This code solves the simple harmonic oscillator equation d^2x/dt^2 = -k*x, where x is the
position and v is the velocity of the oscillator. The solution is then plotted using matplotlib.

Code:
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt

# Define the function representing the first-order differential equation


def harmonic_oscillator(t, y):
"""
Defines the differential equation for a simple harmonic oscillator:
d^2x/dt^2 = -k*x
"""
k = 1.0 # Spring constant
x, v = y[0], y[1]
dxdt = v
dvdt = -k * x
return [dxdt, dvdt]

# Define initial conditions


initial_conditions = [1.0, 0.0] # initial position and velocity

# Define time span


t_span = (0, 10) # from t=0 to t=10

# Solve the differential equation using solve_ivp


sol = solve_ivp(harmonic_oscillator, t_span, initial_conditions, t_eval=np.linspace(0, 10,
100))

# Plot the solution


plt.plot(sol.t, sol.y[0], label='Position (x)')
plt.plot(sol.t, sol.y[1], label='Velocity (v)')
plt.xlabel('Time')
plt.ylabel('Position/Velocity')
plt.title('Simple Harmonic Oscillator')
plt.legend()
plt.grid(True)
plt.show()
Output:

Case Study 2:
Let's consider a classic problem in mechanical engineering: a damped harmonic oscillator. This is a
system that includes both a spring force and a damping force, which could model various physical
systems like a mass attached to a spring moving through a fluid.
In this code, the system is a damped harmonic oscillator with damping ratio zeta and natural
frequency omega_n. The equation of motion is solved numerically using solve_ivp from SciPy, and
the position and velocity versus time are plotted using Matplotlib. This problem is relevant in
various mechanical engineering applications, including vibration analysis and control systems.

Code:

import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt

# Define the function representing the first-order differential equation


def damped_harmonic_oscillator(t, y):
"""
Defines the differential equation for a damped harmonic oscillator:
d^2x/dt^2 = -2*zeta*omega_n*dx/dt - omega_n^2*x
"""
omega_n = 1.0 # Natural frequency
zeta = 0.2 # Damping ratio
x, v = y[0], y[1]
dxdt = v
dvdt = -2 * zeta * omega_n * v - omega_n**2 * x
return [dxdt, dvdt]

# Define initial conditions


initial_conditions = [1.0, 0.0] # initial position and velocity

# Define time span


t_span = (0, 10) # from t=0 to t=10

# Solve the differential equation using solve_ivp


sol = solve_ivp(damped_harmonic_oscillator, t_span, initial_conditions, t_eval=np.linspace(0,
10, 100))

# Plot the solution


plt.plot(sol.t, sol.y[0], label='Position (x)')
plt.plot(sol.t, sol.y[1], label='Velocity (v)')
plt.xlabel('Time')
plt.ylabel('Position/Velocity')
plt.title('Damped Harmonic Oscillator')
plt.legend()
plt.grid(True)
plt.show()
Output:

Case Study 3:
Project involving basic machine learning.

This code performs the following steps:

 Loading Data: Load the Iris dataset using load_iris() function from scikit-learn.
 Data Splitting: Split the dataset into training and testing sets using train_test_split().
 Data Preprocessing: Standardize the features using StandardScaler() to ensure that each
feature has a mean of 0 and a standard deviation of 1
 Model Training: Initialize and train a logistic regression model using LogisticRegression().
 Model Evaluation: Make predictions on the test set and evaluate the model's performance
using accuracy and classification report.

This is a simple example of a machine learning project, but it demonstrates the basic steps involved
in training and evaluating a model. You can further extend this project by trying different algorithms
tuning hyperparameters, or working with more complex datasets.

Code:

# Importing necessary libraries


from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report

# Load the Iris dataset


iris = load_iris()
X = iris.data
y = iris.target

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Feature scaling (standardization)


scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Initialize and train a logistic regression model


model = LogisticRegression()
model.fit(X_train_scaled, y_train)

# Make predictions on the test set


y_pred = model.predict(X_test_scaled)

# Evaluate the model


accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
# Display classification report
print("Classification Report:")
print(classification_report(y_test, y_pred))

Output:

You might also like