Mech Python
Mech Python
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.
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.
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.
Output:
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
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
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:
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:
import os
os.mkdir("dir1")
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:
calculator = Calculator()
result = calculator.add(7, 5)
print("7 + 5 =", 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:
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:
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 = []
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:
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:
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.bind("<B1-Motion>", self.draw)
def main():
root = tk.Tk()
app = CanvasApp(root)
root.mainloop()
if __name__ == "__main__":
main()
Output:
Experiment No. 8
OpenCV in Python
In Matplotlib, this is performed using the imshow() function. Here we have grabbed the plot
object.
Program:
import cv2
from matplotlib import pyplot as plt
import numpy as np
img = cv2.imread('wp.jpg')
plt.show()
cv2.imshow("Mask", mask)
cv2.imshow("Mask Image", masked)
cv2.waitKey(0)
Output:
Experiment No. 9
Theory:
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.
● Import the necessary libraries: import numpy as np and import scipy as sp.
● Load or generate your dataset using NumPy or pandas.
● 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
Aim :- Write python program to use SciPy to solve a linear algebra problem
Program:
import numpy as np
from scipy.linalg import solve
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
Output:
Experiment No. 11
Program:
import cv2
import numpy as np
from matplotlib import pyplot as plt
# 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)
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
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
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
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
Case Study 3:
Project involving basic machine learning.
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:
Output: