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

Python Lap Manual.(2)-1

The document outlines experiments conducted in a Python programming course, focusing on data types, control statements, functions, classes, objects, exception handling, inheritance, and file manipulation. It includes code examples for various Python constructs such as strings, lists, dictionaries, sets, tuples, and file operations. Each experiment aims to enhance understanding of Python programming concepts through practical coding exercises.

Uploaded by

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

Python Lap Manual.(2)-1

The document outlines experiments conducted in a Python programming course, focusing on data types, control statements, functions, classes, objects, exception handling, inheritance, and file manipulation. It includes code examples for various Python constructs such as strings, lists, dictionaries, sets, tuples, and file operations. Each experiment aims to enhance understanding of Python programming concepts through practical coding exercises.

Uploaded by

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

!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

EXPERIMENT 1
AIM: Exploring basics of python like data types (strings, list, array, dictionaries, set, and
tuples) and control statements.
THEORY:
Python has five standard Data Types:

• Numbers

• String

• List

• Tuple

• Dictionary

Python sets the variable type based on the value that is assigned to it. Unlike more riggers
Languages, Python will change the variable type if the variable value is set to another value.

1. STRING

a) Write a Python program to calculate the length of

a string.Python Code:

def string_length(str1):

count = 0

for char in str1:

count += 1

return count

print(string_length('w3resource.com'))

Sample Output:
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering
1
LIST

b) Write a Python program to sum all the items in a list.


Python Code:

def sum_list(items):

sum_numbers = 0

for x in items:

sum_numbers += x

return sum_numbers

print(sum_list([1,2,-8]))

Output:

-
5

DICTIONARY

Write a Python program to sort (ascending and descending) a dictionary by


value.

Python Code:
import operator

d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

print('Original dictionary : ',d)

sorted_d = sorted(d.items(), key=operator.itemgetter(0))

print('Dictionary in ascending order by value : ',sorted_d)


!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True)

print('Dictionary in descending order by value : ',sorted_d)

Output:

Original dictionary : {0: 0, 1: 2, 2: 1, 3: 4, 4: 3}


Dictionary in ascending order by value : [(0, 0), (1, 2), (2, 1), (3, 4),
(4, 3)]

TUPLE.

c) Write a Python program to create a tuple with numbers and print

one item.Python Code:

>>> #Create a tuple with numbers

>>> tuplex = 5, 10, 15, 20, 25

>>> print(tuplex)

>>> #Create a tuple of one item

>>> tuplex = 5,

>>> print(tuplex)

Sample Output:
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

SET

d) Write a Python program to create a new empty set.

Python Code:

#Create a new empty set

x = set()

print(x)

#Create a non empty set

n = set([0, 1, 2, 3, 4])

print(n)

Output:

set()
{0, 1, 2, 3, 4}

ARRAY

e) Write a Python program to create an array of 5 integers and display the


array items. Access individual element through indexes.

Python Code :

from array import *

array_num = array('i', [1,3,5,7,9])

for i in array_num:
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

print(i)

print("Access first three items individually")

print(array_num[0])

print(array_num[1])

print(array_num[2]

Output:

Access first three items individually

Conclusion: Hence we have performed various data types (strings, list, array, dictionaries,
set, and tuples) and control statements.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 2
Aim: Creating functions, classes and objects using python. Demonstrate exception handling
and inheritance.
THEORY:
Syntax to create a function:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Creating Classes
The class statement creates a new class definition. The name of the class immediately follows
the keyword class followed by a colon as follows −
class ClassName:
'Optional class documentation string'
class_suite
• The class has a documentation string, which can be accessed via ClassName. doc .
• The class_suite consists of all the component statements defining class members, data
attributes and functions.

Creating Instance Objects


To create instances of a class, you call the class using class name and pass in whatever
arguments its init method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Inheritance
Inheritance is a powerful feature in object oriented programming.
It refers to defining a new class with little or no modification to an existing class. The new class
is called derived (or child) class and the one from which it inherits is called the base (or parent)
class.
Python Inheritance Syntax
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Derived class inherits features from the base class, adding new features to it. This results into
re- usability of code.

Method Overriding in Python


In the below program, notice that init () method was defined in both classes, Triangle as
well
Polygon. When this happens, the method in the derived class overrides that in the base class.
This is to say, init () in Triangle gets preference over the same in Polygon. Generally when
overriding a base method, we tend to extend the definition rather than simply replace it. The
same is being done by calling the method in base class from the one in derived class (calling
Polygon. init () from init () in Triangle).
A better option would be to use the built-in function super(). So, super(). init (3) is
equivalent to Polygon. init (self,3) and is preferred. You can learn more about the super()
function in Python.
Two built-in functions isinstance() and issubclass() are used to check inheritances. Function is
instance() returns True if the object is an instance of the class or other classes derived from it.
Each and every class in Python inherits from the base class object.

Handling an exception

If you have some suspicious code that may raise an exception, you can defend your
program byplacing the suspicious code in a try: block. After the try: block, include an
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

except: statement, followed by a block of code which handles the problem as


elegantly as possible.

Syntax

Here is simple syntax of try....except...else

blocks −try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute
this block.

except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax −

• A single try statement can have multiple except statements. This is useful
when the tryblock contains statements that may throw different types of
exceptions.
• You can also provide a generic except clause, which handles any exception.
• After the except clause(s), you can include an else-clause. The code in the
else-blockexecutes if the code in the try: block does not raise an exception.

• The else-block is a good place for code that does not need the try: block's
protection.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Function’s:

a) Write a Python function to calculate the factorial of a number (a non-negative


integer).The function accepts the number as an argument.

Python Code:

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

n=int(input("Input a number to compute the factiorial : "))

print(factorial(n))

Output:

Input a number to compute the factiorial : 4


24
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Class
a) Write a Python program to get all possible unique subsets from a set of distinct
integers.

class py_solution:

def sub_sets(self, sset):

return self.subsetsRecur([], sorted(sset))

def subsetsRecur(self, current, sset):

if sset:

return self.subsetsRecur(current, sset[1:]) +


self.subsetsRecur(current +[sset[0]], sset[1:])

return [current]

print(py_solution().sub_sets([4,5,6]))

Output:

[[], [6], [5], [5, 6], [4], [4, 6], [4, 5], [4, 5, 6]]

Handling an exception

PROGRAM:

class Error(Exception):

pass

def main():

str=input("Enter a

string")try:
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

if len(str)<=6:

raise

ValueErr

or

except

ValueErr

or:

print("Please enter a valid

String\t")main()

main()

Output:

Conclusion:

Hence we create functions, classes and objects exception handling and inheritance
using python
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 3
AIM: Exploring Files and directories

THEORY:

Opening and Closing Files


Until now, you have been reading and writing to the standard input and output. Now,
we will seehow to use actual data files.

Python provides basic functions and methods necessary to manipulate files by default.
You cando most of the file manipulation using a file object.

The open Function


Before you can read or write a file, you have to open it using Python's built-in open()
function.This function creates a file object, which would be utilized to call other
support methods associated with it.

Syntax
file object = open(file_name [, access_mode][,

buffering])Here are parameter details −

• file_name − The file_name argument is a string value that contains the name
of the filethat you want to access.
• access_mode − The access_mode determines the mode in which the file has to
be opened, i.e., read, write, append, etc. A complete list of possible values is
given below inthe table. This is optional parameter and the default file access
mode is read (r).
• buffering − If the buffering value is set to 0, no buffering takes place. If the
buffering value is 1, line buffering is performed while accessing a file. If you
specify the bufferingvalue as an integer greater than 1, then buffering action is
performed with the indicated buffer size. If negative, the buffer size is the
system default(default behavior).
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Here is a list of the different modes of opening a file –

Sr.No. Modes & Description

1 R

Opens a file for reading only. The file pointer is placed at the beginning of the file. This
is the default mode.
Rb
2
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
r+
3
Opens a file for both reading and writing. The file pointer placed at the beginning of the
file.
rb+
4
Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.
W
5
Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
Wb
6
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
w+
7
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.
wb+
8
Opens a file for both writing and reading in binary format. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and writing.
A
9
Opens a file for appending. The file pointer is at the end of the file if the file exists. That
is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Ab
10
Opens a file for appending in binary format. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.
11 a+

Opens a file for both appending and reading. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.
ab+
12
Opens a file for both appending and reading in binary format. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the file does not
exist, it creates a new file for reading and writing.
The file Object Attributes

Once a file is opened and you have one file object, you can get various information
related to thatfile. Here is a list of all attributes related to file object −

Sr.No. Attribute & Description

file.closed
1
Returns true if file is closed, false otherwise.
file.mode
2
Returns access mode with which file was opened.
file.name
3
Returns name of the file.

file.softspace
4
Returns false if space explicitly required with print, true otherwise.

PROGRAM:

file_append=open("D:/test.txt","a"
)

file_append.write("\nPython is a language")
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

print("The file is appended")


file_append.close()

count=len(open("D:/test.txt").readl
ines())

print("The number of lines in the file are: ",count)

text=open("D:/test
.txt",'r+')
wordcount={}
str=text.read()

for word in str.split():

if word not in
wordcount:

wordcount[wor
d]=1

else:
wordcount[
word]+=1

for k,v in
wordcount.items()
:print (k,v)

Output:

Conclusion: Hence we have performed Files and directories in python.


!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 4
Aim: Creating GUI with python containing widgets such as labels, textbox, radio,
checkboxes and custom dialog boxes.

Theory:

Introducing Tkinter :

Although there are other GUI development alternatives in Python, Tkinter is the most popular.

An ordinary Python library is Tkinter. The quickest and simplest approach to create an object-
oriented GUI application is with Python and the tkinter package.

It offers us a number of standard GUI (graphical user interface) building blocks, such as
buttons, menus, and other types of entry fields and display regions, that we may utilise to create
our user interfaces.

Some of the common widgets used in Tkinter are :

o Frame : serves as a holding area for other widgets and serves as a container.
o Text : It enables us to display and alter text in a variety of styles and offers a prepared
text display.
o Label : Used to display text and images, but we are unable to interact with it.
o Button : Often used add buttons and we may add functions and methods to it.
o Entry : One-line string text can be entered into this widget.
o Labelframe : For intricate window layouts, this widget serves as a separator or
container.
o Listbox : It just has text elements, all of which are the same colour and font.
o Scrollbar: This gives a sliding controller.
o Canvas : Custom widgets can be implemented using the canvas widget.
o Scale : This widget offers graphical slider items that let us choose different scale values.
o Radiobutton : Use a radio button to carry out one of several choices.
o Checkbox : Use a checkbox to implement on-off choices.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

o Listbox : It just has text elements, all of which are the same colour and font.

#Creating a simple GUI registration form using Tkinter in Python


#import the tkinter module into our code
from tkinter import *
#Creating the object 'base' of the Tk()
base = Tk()

#Using the Geometry method to the form certain dimensions


base.geometry("550x550")

#Using title method to give the title to the window


base.title('Registration form')

#Now, we will use 'Label' method to add widget in the Registration Form and also use place()
method to set their positions.
lbl_0 = Label(base, text="Registration form", width=20,font=("bold",20))

#the place method in tkinter module helps user to set the geometry, that is, the dimensions of
a certain widget by placing them at a certain position
lbl_0.place(x=90,y=60)

#Using 'Label' widget to create Full name label and using place() method to set its position.
lbl_1 =Label(base, text= "FullName", width=20,font=("bold",10))
lbl_1.place(x=80,y=130)

#Using Enrty widget to make a text entry box for accepting the input string in text from user.
enter_1 = Entry(base)
enter_1.place(x=240,y=130)

#Using 'Label' widget to create Email label and using place() method to set its position.
lbl_3 = Label(base, text="Email", width=20,font=("bold",10))
lbl_3.place(x=68,y=180)

#Using Enrty widget to make a text entry box for accepting the input string in text from user.
enter_3 = Entry(base)
enter_3.place(x=240,y=180)

#Using 'Label' widget to create Gender label and using place() method to set its position.
lbl_4 = Label(base, text="Gender", width=20,font=("bold",10))
lbl_4.place(x=70,y=230)
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

#Using variable 'vars' to store the integer value, which by deault is 0


vars = IntVar()

#Using Radio button widget to create an option choosing button and using place() method to
set its position.
Radiobutton(base, text="Male", padx= 5, variable= vars, value=1).place(x=235, y=230)
Radiobutton(base, text="Female", padx= 20, variable= vars, value=2).place(x=290,y=230)

#Using 'Label' widget to create Countries label and using place() method, set its position.
lbl_5=Label(base, text ="Country", width=20,font=("bold",11))
lbl_5.place(x=70,y=280)

#this creates list of countries available in the dropdown list.


list_of_cntry=[ 'India' ,'Canada' , 'US' ,'Germany' ,'UK']

#the variable 'cv' is introduced to store the String Value, which by default is (empty) ""
cv = StringVar()
drplist = OptionMenu(base, cv, *list_of_cntry)
drplist.config(width=15)
cv.set('Select your Country')
drplist.place(x=240, y=280)

#Using 'Label' widget to create Language label and using place() method, set its position.
lbl_6=Label(base, text="Language", width=20,font=('bold',10))
lbl_6.place(x=75,y=330)

#the new variable 'vars1' is created to store Integer Value, which by default is 0.
vars1=IntVar()
#Using the Checkbutton widget to create a button and using place() method to set its position.
Checkbutton(base,text="English", variable = vars1).place(x=230,y=330)

#the new variable 'vars1' is created to store Integer Value, which by default is 0.
vars2=IntVar()
#Using the Checkbutton widget to create a button and using place() method to set its position.
Checkbutton(basetext="German", variable=vars2).place(x=290, y=330)

#Using the Button widget, we get to create a button for submitting all the data that has been e
ntered in the entry boxes of the form by the user.
Button(base, text='Submit' , width=20, bg="black",fg='white').place(x=180,y=380)

#Calling the mainloop method to execute the entire program.


!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

base.mainloop()

Output:

Conclusion: Hence we have performed GUI with python containing widgets such as labels,
textbox, radio, checkboxes and custom dialog boxes.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 5
Aim: Menu driven program for data structure using built in function for link list, stack and
queue.

Theory:

Data Structure:
Organizing, managing and storing data is important as it enables easier access and efficient
modifications. Data Structures allows you to organize your data in such a way that enables you
to store collections of data, relate them and perform operations on them accordingly.

Types of Data Structures in Python


Python has implicit support for Data Structures which enable you to store and access data.
These structures are called List, Dictionary, Tuple and Set.

Python allows its users to create their own Data Structures enabling them to have full
control over their functionality. The most prominent Data Structures are Stack, Queue, Tree,
Linked List and so on which are also available to you in other programming languages. So now
that you know what are the types available to you, why don’t we move ahead to the Data
Structures and implement them using Python.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Program:

print('push <value>')

a_stack.push(int(do[1]))
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Output:

Case 1:
push <value>
pop
quit
What would you like to do? push 15
push <value>
pop
quit
What would you like to do? push 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 15
push <value>
pop
quit
What would you like to do? pop
Stack is empty.
push <value>
pop
quit
What would you like to do? quit

Case 2:
push <value>
pop
quit
What would you like to do? pop
Stack is empty.
push <value>
pop
quit
What would you like to do? quit

Conclusion:
Hence we have performed Menu driven program for data structure using built in
function for link list, stack and queue.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No. 6
Aim: Program to demonstrate CRUD (create, read, update and delete) operations on database
(SQLite/ MySQL) using python.

Program:

import sqlite3
connection =

sqlite3.connect("company.db")cursor

= connection.cursor()

# delete

#cursor.execute("""DROP TABLE employee;""")

sql_command =
""" CREATE
TABLE employee
(

staff_number INTEGER
PRIMARY KEY,fname
VARCHAR(20),

lname VARCHAR(30),
gender
CHAR(1),
joining
DATE,
birth_date
DATE);"""

cursor.execute(sql_command)

sql_command = """INSERT INTO employee (staff_number, fname, lname,


gender,birth_date)

VALUES (NULL, "William", "Shakespeare", "m", "1961-10-25");"""

cursor.execute(sql_command)
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

sql_command = """INSERT INTO employee (staff_number, fname, lname,


gender,birth_date)

VALUES (NULL, "Frank", "Schiller", "m", "1955-08-17");"""


cursor.execute(sql_command)

# never forget this, if you want the changes to be saved:


connection.commit()

connection.close()

import sqlite3

connection =

sqlite3.connect("company.db")cursor

= connection.cursor()

staff_data = [ ("William", "Shakespeare", "m", "1961-10-25"),

("Frank", "Schiller", "m", "1955-08-17"),

("Jane", "Wall", "f", "1989-03-14") ]

for p in staff_data:

format_str = """INSERT INTO employee (staff_number, fname, lname,


gender,birth_date)

VALUES (NULL, "{first}", "{last}", "{gender}", "{birthdate}");"""

sql_command = format_str.format(first=p[0], last=p[1],


gender=p[2],birthdate = p[3])

cursor.execute(sql_command)

import sqlite3

connection = sqlite3.connect("company.db")

cursor = connection.cursor()
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

cursor.execute("SELECT * FROM
employee")print("fetchall:")

result =
cursor.fetchall()
for r in result:

print(r)

cursor.execute("SELECT * FROM
employee")print("\nfetch one:")

res =
cursor.fetchone(
)print(res)

Output:

fetchall:

(1, 'William', 'Shakespeare', 'm', None, '1961-10-25')

(2, 'Frank', 'Schiller', 'm', None, '1955-08-17')

fetch one:

(1, 'William', 'Shakespeare', 'm', None, '1961-10-25')

>>>

Conclusion:
Hence we have performed various CRUD operations in python.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No. 7
Aim: Creation of simple socket for basic information exchange between server and client.

Theory:

A simple server-client program :


Server
A server has a bind() method which binds it to a specific ip and port so that it can listen
to incoming requests on that ip and port.A server has a listen() method which puts the
server into listen mode. This allows the server to listen to incoming connections. And last
a server has an accept() and close() method. The accept method initiates a connection
with the client and the close method closes the connection with the client.

import socket
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)import socket
# next create a
socket objects =
socket.socket()
print ("Socket successfully created")
# reserve a port on your
computer in our# case it is
12345 but it can be anything
port = 12345
# Next bind to the port
# we have not typed any ip in the
ip field # instead we have
inputted an empty string# this
makes the server listen to
requests
# coming from other computers on the
networks.bind(('', port))
print ("socket binded to %s"
%(port))# put the socket
into listening mode
s.listen(5)
print ("socket is listening" )
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

# a forever loop until we


interrupt it or# an error occurs
while True:

# Establish connection
with client.c, addr =
s.accept()
print ('Got connection from', addr)
# send a thank you message to
the client.c.send('Thank you for
connecting')
# Close the connection with
the clientc.close()

output
# in the server.py terminal you will see

# this output:

Socket successfully created

socket binded to 12345

socket is listening

Got connection from ('127.0.0.1', 52617)

# In the telnet terminal you will get this:

Trying ::1...

Trying 127.0.0.1...

Connected to localhost.

Now for the client side:


# Import socket
moduleimport
socket

# Create a socket
objects =
socket.socket()

# Define the port on which you want to connect


!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

port = 12345

# connect to the server on local


computers.connect(('127.0.0.1',
port))

# receive data from the


serverprint s.recv(1024)

# close the
connection
s.close()

output
# start the server:

$ python server.py

Socket successfully created

socket binded to 12345

socket is listening

Got connection from ('127.0.0.1', 52617)

# start the client:

$ python client.py

Conclusion: Hence we performed creation of simple socket for basic information exchange
between server and client.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 8
Aim: Programs on Threading using python.

Theory:

Multithreading is a threading technique in Python programming to run multiple threads


concurrently by rapidly switching between threads with a CPU help (called context switching).
Besides, it allows sharing of its data space with the main threads inside a process that share
information and communication with other threads easier than individual processes.
Multithreading aims to perform multiple tasks simultaneously, which increases performance,
speed and improves the rendering of the application.

Program:

import thread # import the thread module


import time # import time module

def cal_sqre(num): # define the cal_sqre function


print(" Calculate the square root of the given number")
for n in num:
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)

def cal_cube(num): # define the cal_cube() function


print(" Calculate the cube of the given number")
for n in num:
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n *n)

arr = [4, 5, 6, 7, 2] # given array

t1 = time.time() # get total time to execute the functions


cal_sqre(arr) # call cal_sqre() function
cal_cube(arr) # call cal_cube() function
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

print(" Total time taken by threads is :", time.time() - t1) # print the total time

Output:

Calculate the square root of the given number


Conclusion: Hence we performed threading using python. Square is: e is: 25
Square is: 36
Square

is: 49
Square is: 4
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 9
Aim: Exploring basics of NumPy Methods

Theory:

The NumPy library is a popular Python library used for scientific computing applications, and
is an acronym for "Numerical Python".

NumPy's operations are divided into three main categories: Fourier Transform and Shape
Manipulation, Mathematical and Logical Operations, and Linear Algebra and Random Number
Generation. To make it as fast as possible, NumPy is written in C and Python.

Program:

import numpy as np

# Creating 5x4 array


array = np.arange(20).reshape(5, 4)
print(array)
print()

# If no axis mentioned, then it works on the entire array


print(np.argmax(array))

# If axis=1, then it works on each row


print(np.argmax(array, axis=1))

# If axis=0, then it works on each column


print(np.argmax(array, axis=0))

Output:

[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]

19
[3 3 3 3 3]
[4 4 4 4]: 216
Conclusion: Hence we performed NumPy Methods
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 10
Aim: Program to demonstrate use of NumPy: Array objects.
Cube is: 8
Theory:

Numpy Applications
1. An alternative for lists and arrays in Python
Arrays in Numpy are equivalent to lists in python. Like lists in python, the Numpy arrays are
homogenous sets of elements. The most important feature of NumPy arrays is they are
homogenous in nature.

This differentiates them from python arrays. It maintains uniformity for mathematical
operations that would not be possible with heterogeneous elements. Another benefit of using
NumPy arrays is there are a large number of functions that are applicable to these arrays.

These functions could not be performed when applied to python arrays due to their
heterogeneous nature.

2. NumPy maintains minimal memory


Arrays in NumPy are objects. Python deletes and creates these objects continually, as per the
requirements. Hence, the memory allocation is less as compared to Python lists. NumPy has
features to avoid memory wastage in the data buffer.

It consists of functions like copies, view, and indexing that helps in saving a lot of memory.
Indexing helps to return the view of the original array, that implements reuse of the data. It also
specifies the data type of the elements which leads to code optimization.

3. Using NumPy for multi-dimensional arrays


We can also create multi-dimensional arrays in NumPy.These arrays have multiple rows and
columns. These arrays have more than one column that makes these multi-dimensional. Multi-
dimensional array implements the creation of matrices.

These matrices are easy to work with. With the use of matrices the code also becomes memory
efficient. We have a matrix module to perform various operations on these matrices.

4. Mathematical operations with NumPy


Working with NumPy also includes easy to use functions for mathematical computations on
the array data set. We have many modules for performing basic and special mathematical
functions in NumPy.

There are functions for Linear Algebra, bitwise operations, Fourier transform, arithmetic
operations, string operations, etc.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Numpy Array Applications


1. Shape Manipulations
Users can change array dimensions at runtime if the output produces the same number of
elements. We apply np.reshape(…)function on the array. The reshape function is useful for
performing various operations. For eg, we use it when we want to broadcast two dissimilar
arrays.

2. Array Generation
We can generate array data set for implementing various functions. We can also generate a
predefined set of numbers for the array elements using the np.arrange(…)function. Reshape
function is useful to generate a different set of dimensions.

We can also use the random function to generate an array having random values. Similarly, we
can use linspace function to generate arrays having similar spacing in elements.

We can create arrays with pre-filled ones or zeroes. The default data type is set to be float64
but we can edit the data type using dtype option.

3. Array Dimensions
Numpy consists of both one and multidimensional arrays. Some functions have restrictions on
multidimensional arrays. It is then necessary to transform those arrays into one-dimensional
arrays. We can transform multi-dimensional to single dimension using np.ravel(..)

Numpy Applications with Other Libraries


1. NumPy with Pandas
Pandas is one of the most important libraries in python for data analysis. Pandas provide high
performance, fast analysis, and data cleaning. We use it to manipulate data structures and have
data analysis tools.

It consists of a data frame object. It interoperates with NumPy for faster computations. When
we use both the libraries together it is a very helpful resource for scientific computations.

2. NumPy with Matplotlib


Matplotlib is a module in NumPy. It is a very helpful tool to work with graphical
representations. It consists of a wide range of functions to plot graphs and also manipulate
them.

This combination can replace the functionalities of MatLab. It is used to generate the graphs
of the results. We enhance it further with the use of graphic toolkits like PyQt and wxPython.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

3. NumPy with SciPy


Scipy is an open-source library in Python. It is the most important scientific library in python.
It has been built upon the functionalities of NumPy.There are advanced functionalities in SciPy
for scientific computations.

We can combine it with NumPy for greater mathematical performance. The combination helps
in the implementation of complex scientific operations.

4. NumPy with Tkinter


Tkinter is a standard library for GUI. We use Tkinter for the GUI representation of the NumPy
data. Its combination with NumPy can implement fast and easy GUIs. The use of Tkinter along
with NumPy is user friendly. We can easily convert the array objects into image objects.

Program:

reshape a numpy array of shape (3, 4) to (2, 6).

import numpy as np

# reshape (3, 4) array to (6, 2)


arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

shape = (6, 2)
output = np.reshape(arr, shape)

print(output)

Output:

[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]]

Conclusion: Hence we performed NumPy use of NumPy: Array objects.


!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 11
Aim: Program to demonstrate .

Theory:
Series is a type of list in Pandas that can take integer values, string values, double values, and
more. But in Pandas Series we return an object in the form of a list, having an index starting
from 0 to n, Where n is the length of values in the series. Series can only contain a single list
with an index, whereas Dataframe can be made of more than one series or we can say that a
Dataframe is a collection of series that can be used to analyze the data.

Program

# importing pandas library


import pandas as pd

# Creating a list
author = ['Jitender', 'Purnima',
'Arpit', 'Jyoti']
# Creating a Series by passing list
# variable to Series() function
auth_series = pd.Series(author)
# Printing Series
print(auth_series)

Output:.

0 Jitender
1 Purnima
2 Arpit
3 Jyoti
dtype: object

check the type of Series:


print(type(auth_series))

Output:
<class 'pandas.core.series.Series'>
Conclusion: Hence we performed Data Series and Data Frames using Pandas.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 12

Aim: Program to send email and read content of URL.


Theory:
Python offers a ` library to send emails- “SMTP lib”. “smtplib” creates a Simple Mail
Transfer Protocol client session object which is used to send emails to any valid email id on
the internet. The Port number used here is ‘587’. And if you want to send mail using a website
other than Gmail.

Send mail from a Gmail account


Here we are going to send the mail from gmail using Python.
Step 1: First of all, “smtplib” library needs to be imported.
Step 2: After that create a session, we will be using its instance SMTP to encapsulate an
SMTP connection.
s = smtplib.SMTP('smtp.gmail.com', 587)
Step 3: In this, you need to pass the first parameter of the server location and the second
parameter of the port to use. For Gmail, we use port number 587.
Step 4: For security reasons, now put the SMTP connection in TLS mode. TLS (Transport
Layer Security) encrypts all the SMTP commands. After that, for security and authentication,
you need to pass your Gmail account credentials in the login instance. The compiler will
show an authentication error if you enter an invalid email id or password.
Step 5: Store the message you need to send in a variable say, message. Using the sendmail()
instance, send your message. sendmail() uses three parameters: sender_email_id,
receiver_email_id and message_to_be_sent. The parameters need to be in the same
sequence.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Code

import smtplib
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)

# start TLS for security


s.starttls()

# Authentication
s.login("sender_email_id", "sender_email_id_password")

# message to be sent
message = "Message_you_need_to_send"

# sending the mail


s.sendmail("sender_email_id", "receiver_email_id", message)

# terminating the session


s.quit()

Send email to multiple recipients using Python

import smtplib

# list of email_id to send the mail


li = ["[email protected]", "[email protected]"]
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

for dest in li:


s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("sender_email_id", "sender_email_id_password")
message = "Message_you_need_to_send"
s.sendmail("sender_email_id", dest, message)
s.quit()

Conclusion:
Hence we have performed how to send email and read content of URL in python.
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 13

Aim: Solving and plotting differential equations

Program

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

def f(s,t):
a=4
b=7
n = s[0]
c = s[1]
dndt = a * n - (c/(c+1)) * b * n
dcdt = (c/(c+1)) * n - c + 1
return [dndt, dcdt]

t = np.linspace(0,20)
s0=[20,5]

s = odeint(f,s0,t)

plt.plot(t,s[:,0],'y--', linewidth=2.0)
plt.plot(t,s[:,1],'b-', linewidth=2.0)
plt.xlabel("t")
plt.ylabel("S[N,C]")
plt.legend(["N","C"])
plt.show()
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Output:
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Experiment No 14
Aim: Solving and plotting differential equations

Program

import numpy as np
def pend(y, t, b, c):
theta, omega = y
dydt = [omega, -b*omega - c*np.sin(theta)]
return dydt
b = 0.25
c = 5.0
y0 = [np.pi - 0.1, 0.0]
t = np.linspace(0, 10, 101)
from scipy.integrate import odeint
sol = odeint(pend, y0, t, args=(b, c))
import matplotlib.pyplot as plt
plt.plot(t, sol[:, 0], 'b', label='theta(t)')
plt.plot(t, sol[:, 1], 'g', label='omega(t)')
plt.legend(loc='best')
plt.xlabel('t')
plt.grid()
plt.show()
!! Sabka Malik Atma !!

Vishwatmak Jangli Maharaj Ashram Trust’s

Atma Malik Institute of Technology & Research (AMRIT)


Department of Mechanical Engineering

Output:

You might also like