Python Lap Manual.(2)-1
Python Lap Manual.(2)-1
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 string.Python Code:
def string_length(str1):
count = 0
count += 1
return count
print(string_length('w3resource.com'))
Sample Output:
!! Sabka Malik Atma !!
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
Python Code:
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Output:
TUPLE.
>>> print(tuplex)
>>> tuplex = 5,
>>> print(tuplex)
Sample Output:
!! Sabka Malik Atma !!
SET
Python Code:
x = set()
print(x)
n = set([0, 1, 2, 3, 4])
print(n)
Output:
set()
{0, 1, 2, 3, 4}
ARRAY
Python Code :
for i in array_num:
!! Sabka Malik Atma !!
print(i)
print(array_num[0])
print(array_num[1])
print(array_num[2]
Output:
Conclusion: Hence we have performed various data types (strings, list, array, dictionaries,
set, and tuples) and control statements.
!! Sabka Malik Atma !!
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.
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.
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 !!
Syntax
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.
• 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 !!
Function’s:
Python Code:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(n))
Output:
Class
a) Write a Python program to get all possible unique subsets from a set of distinct
integers.
class py_solution:
if sset:
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 !!
if len(str)<=6:
raise
ValueErr
or
except
ValueErr
or:
String\t")main()
main()
Output:
Conclusion:
Hence we create functions, classes and objects exception handling and inheritance
using python
!! Sabka Malik Atma !!
Experiment No 3
AIM: Exploring Files and directories
THEORY:
Python provides basic functions and methods necessary to manipulate files by default.
You cando most of the file manipulation using a file object.
Syntax
file object = open(file_name [, access_mode][,
• 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 !!
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 !!
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 −
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 !!
count=len(open("D:/test.txt").readl
ines())
text=open("D:/test
.txt",'r+')
wordcount={}
str=text.read()
if word not in
wordcount:
wordcount[wor
d]=1
else:
wordcount[
word]+=1
for k,v in
wordcount.items()
:print (k,v)
Output:
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.
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 !!
o Listbox : It just has text elements, all of which are the same colour and font.
#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 !!
#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)
#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)
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 !!
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.
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 !!
Program:
print('push <value>')
a_stack.push(int(do[1]))
!! Sabka Malik Atma !!
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 !!
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
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)
cursor.execute(sql_command)
!! Sabka Malik Atma !!
connection.close()
import sqlite3
connection =
sqlite3.connect("company.db")cursor
= connection.cursor()
for p in staff_data:
cursor.execute(sql_command)
import sqlite3
connection = sqlite3.connect("company.db")
cursor = connection.cursor()
!! Sabka Malik Atma !!
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:
fetch one:
>>>
Conclusion:
Hence we have performed various CRUD operations in python.
!! Sabka Malik Atma !!
Experiment No. 7
Aim: Creation of simple socket for basic information exchange between server and client.
Theory:
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 !!
# 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 is listening
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
# Create a socket
objects =
socket.socket()
port = 12345
# close the
connection
s.close()
output
# start the server:
$ python server.py
socket is listening
$ python client.py
Conclusion: Hence we performed creation of simple socket for basic information exchange
between server and client.
!! Sabka Malik Atma !!
Experiment No 8
Aim: Programs on Threading using python.
Theory:
Program:
print(" Total time taken by threads is :", time.time() - t1) # print the total time
Output:
is: 49
Square is: 4
!! Sabka Malik Atma !!
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
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 !!
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.
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.
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.
There are functions for Linear Algebra, bitwise operations, Fourier transform, arithmetic
operations, string operations, etc.
!! Sabka Malik Atma !!
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(..)
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.
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 !!
We can combine it with NumPy for greater mathematical performance. The combination helps
in the implementation of complex scientific operations.
Program:
import numpy as np
shape = (6, 2)
output = np.reshape(arr, shape)
print(output)
Output:
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]]
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
# 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
Output:
<class 'pandas.core.series.Series'>
Conclusion: Hence we performed Data Series and Data Frames using Pandas.
!! Sabka Malik Atma !!
Experiment No 12
Code
import smtplib
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# Authentication
s.login("sender_email_id", "sender_email_id_password")
# message to be sent
message = "Message_you_need_to_send"
import smtplib
Conclusion:
Hence we have performed how to send email and read content of URL in python.
!! Sabka Malik Atma !!
Experiment No 13
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 !!
Output:
!! Sabka Malik Atma !!
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 !!
Output: