Python Lab Manual
Python Lab Manual
For
PYTHON PROGRAMMING LABORATORY
[CS206ES]
ACE
Engineering College
An Autonomous Institution
Ghatkesar, Hyderabad - 501 301,
Telangana. Approved by AICTE &
Affiliated to JNTUH
NBA Accredited [Link] Courses, Accorded NACC A-Grade with
3.20 CGPA
1
INDEX
4 List of Experiments 4
7 Introduction to Lab 7
8 Lab Experiments 16
10 Scheme of Evaluation 43
11 References 44
2
Institute Vision:
To be a leading Technical Institute to prepare high quality Engineers to cater the needs
of the stakeholders in the field of Engineering and Technology with global competence
fundamental comprehensive analytical skills, critical reasoning, research aptitude,
entrepreneur skills, ethical values and social concern.
Institute Mission:
Imparting Quality Technical Education to young Engineers by providing the state-of-
the-art laboratories, quality instructions by qualified and experienced faculty and
research facilities to meet the requirements of stakeholders in real time usage and in
training them to excel in competitive examinations for higher education and employment
to interface globally emerging techno-informative challenges in the growth corridor of
techno-excellence.
Department Vision:
To produce excellent standard, quality education of professionals by imparting cognitive
learning environment, research and industrial orientation to become innovative Data
Science Professional.
Department Mission:
M3. To impart quality and value based education and contribute towards the
innovation of computing system, data science to raise satisfaction level of all
stakeholders
M4. Enabling students to get expertise in critical skills with data science education
and facilitate socially responsive research and innovation.
M5. Our effort is to apply new advancements in high performance computing
hardware and software
3
Program Out comes (POs)
Program Statements
Outcome
s
Analyze and build models applying the knowledge of mathematics, statistics,
PO1
electronic, electrical and computer science discipline and solve the problem.
Identify the sources of information for data collection, design and conduct
PO2 the experiments and interpret the result.
Think out-of-the box and solve the real time problems using their creativity
PO3 in designing human friendly software systems.
PO11 Apply the hardware and software project management techniques to estimate
the time and human resources required to complete computer engineering
projects.
Recognize the need for, and have the preparation and ability to
PO12
engage in independent and life-long learning in the broadest context
of technological change
5
Program Specific Outcomes (PSOs)
Program Statement
Specific
Outcomes
PSO1 Understand, analyze and develop essential proficiency in the areas related to
data science in terms of underlying statistical and computational principles and
apply the knowledge to solve practical problems.
PSO2 Implement data science techniques such as search algorithms, neural networks,
machine learning and data analytics for solving a problem and designing novel
algorithms for successful career and entrepreneurship
6
Course Objectives:
Course Outcomes:
Hardware Requirements:
Processor: Inteli3orhigher
RAM: 4GB
Memory:500GB
Software Requirements:
Python3
7
8
List of Experiments:
9
c) Python Program to Print the Fibonacci sequence using while loop
d) Python program to print all prime numbers in a given interval (use
break)
12
Module wise Outcome:
13
Cos Mapping with Pos and PSOs:
Program PS
Outcome(POs) Os
CO P PO PO PO PO P PO PO PO PO PO PO PS PS PS BT
O1 2 3 4 5 O 7 8 9 10 11 12 O O O L
6 1 2 3
C 3 3 3 3 3 2 1 2,3
O ,6
1
C 3 3 3 3 3 3 3,6
O
2
C 2 3 3 2 3 3 3
O
3
C 3 3 3 3 3 3 3 3,6
O
4
C 1 3 1 3 3 2 2 2 1 3 3 3
O
5
C 3 3 3 3 2 2 2 3 3 3 2 3 3
O
6
2.3 3.0 2.3 2.8 3.0 2.0 2.0 2.0 2.5 2.8 3.0 2.7 2.3
INTRODUCTIONTOLAB:
History :
14
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
Small Talk ,Unix shell, and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Major implementations of Python are Cpython, Iron Python, Jpython, MicroPython, PyPy
Top software companies like Google , Microsoft ,IBM , Yahoo using python
Features
Simple & Easy to Learn
Interpreted
Portable, Extendable
Embedded
15
Databases and GUI Programming
Scientific Applications
Web Applications
Web Scrapping
17
Administration Script
Test Cases
GUI Applications
Gaming Applications
Animation Applications
4. Store the Windows Installer file somewhere on your computer, such as C:\download\ python
[Link] (Just create a directory where you can find it later.)
5. Run the downloaded file by double-clicking it in Windows Explorer. Just accept the default
settings, wait until the installation is finished, and you’re ready to roll!
18
Working with Python Basic Syntax
>>> 2 + 3
>>>
19
Data types
Every value in Python has a data type. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes. There are
various data types in Python. Some of the important types are listed below.
None : Nothing or no value associated
Numbers
List
Tuple
String
Set
Dictionary
Numbers:
Number stores numeric values. Python creates Number objects when a number is assigned to a
variable
Ex: a,b=4,5 # a and b are objects
There are 3 sub types
int : The int data type represents an integer number( 200)
float: The float data type represents floating point number(3.14)
complex: A complex number is a number that is written in the form of a+bj or a+bJ(3.14j,
2-3.5J)
bool: It is used to represent Boolean values(True and False)
Lists:
Lists in python are similar to arrays in C. However the list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed within square brackets
[].We can use slice [:] operators to access the data of the list.
l = [1, "hi", "python", 2]
print (l[2:])
print (l[0:2])
20
Tuple:
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The elements in the tuple are separated with a comma (,) and
enclosed in parentheses ().Whereas the list elements can be modified, it is not possible to
modify the tuple elements
t = (10,5.3,"hi", "python", 2)
print (t[1:]);
print (t[0:1]);
t[3]=77 #Error
String :
A string is represented by group of characters represented in quotation marks. In python,
strings are enclosed in single or double quotes. Multi-line strings can be denoted using triple
quotes, ''' or """. slicing operator [ :] can be used to retrieve parts of string
s=‘hello’
str2=“welcome “
str3 =“ “ “ python ” ” ”
print(s[-4])
print(s[2:])
Dictionary:
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a
huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to
retrieve the value. In Python, dictionaries are defined within braces {} with each item being a
pair in the form key: value. Key and value can be of any type.
d = {1:'value','key':2}
print(d[1])
print(d[‘key’]
Range:
The range data type represents a sequence of numbers. The numbers in the range are not
modifiable. Generally range is used for repeating a for loop for specific number of times. To
create a range of numbers, we can simply write
r=range(10) r=range(2,9)
r=range(1,10,2)
Set:
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered. it means the elements may not appear in the
21
same order as they are entered into the sets
a = {5,2,3,1,4}
print(a)
Type conversion:
The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. It is done by using different type conversion functions like int(),
float(), complex and str() etc.
int():This function converts any data type to integer except complex type
>>>int(23.45) #23
>>>int(“44”) #44
>>>int(True) #1
float():This function is used to convert any data type to a floating point number except complex
type
>>>float(5) #5.0
>>>float(“10.5”) #10.5
>>>float(“10”) #10.0
>>>float(True) #1
Complex(): This function convert other types to complex type
>>>complex(10) #10+0j
>>>complex(False) #0j
>>>complex(“10.5”) #10.5+0j
str(): This function convert other type values to str type
>>>str(10) #’10’
>>>str(True) #’True’
Python Variables
A variable is a location in memory used to store some data(value). The rules for writing a
variable name is same as the rules for writing identifiers in Python. We don't need to declare a
variable before using it. In Python, we simply assign a value to a variable and it will exist.
We don't even have to declare the type of the variable. This is handled internally according to
the type of value we assign to the variable.
Variable assignment
We use the assignment operator (=) to assign values to a variable. Any type of value can be
22
assigned to any valid variable.
Ex: a=5 a=b=c=1
b = 3.2
c = "Hello“
Changing the value of a variable
Ex: a=4
print(a)
a=“hello”
print(a)
Assigning multiple values to multiple variables
Ex: name ,rno , avg = “Hello”, 15, 95.3
Note: Every Variable in Python is a Object
23
Python Indentation :
Most of the programming languages like C, C++, Java use braces { } to define a block
of code .
But Python provides no braces{} to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation
The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent
throughout that block. If a block has to be more deeply nested, it is simply indented
further to the right.
fori in range(1,11):
print(i)
ifi == 5:
break
1. a) i) Use a web browser to go to the Python website [Link] This
page contains information about Python and links to Python-related pages,
and it gives you the ability to search the Python documentation.
Output:
ii) Start the Python interpreter and type help() to start the online help utility
Output:
print(distance)
Output:
6.324555320336759
d) Read name, address, email and phone number of a person through keyboard and
print the details.
Source Code:
Enter a character: A
Uppercase character
Enter a character: 1
Digit
c) Python Program to Print the Fibonacci sequence using while loop
Source Code:
n = int(input("Enter the value of 'n': "))
a=0
b=1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a=b
b = sum
sum = a + b
Output:
Enter the value of 'n': 5
Fibonacci Series: 0 1 1 2 3
d) Python program to print all prime numbers in a given interval (use break)
Source Code:
lower = 100
upper = 200
print("Prime numbers between", lower, "and", upper, "are:")
fornum in range(lower, upper + 1):
# all prime numbers are greater than 1
ifnum> 1:
fori in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Output:
Prime numbers between 100 and 200 are:
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
3.a)i)Write a program to convert a list and tuple into arrays.
Source Code:
importnumpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("List to array: ")
print([Link](my_list))
my_tuple = ([8, 4, 6], [1, 2, 3])
print("Tuple to array: ")
print([Link](my_tuple))
Output:
List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]
b) Writes a recursive function that generates all binary strings of n-bit length
SourceCode:
defprintTheArray(arr, n):
fori in range(0, n):
print(arr[i], end = " ")
print()
# Function to generate all binary strings
defgenerateAllBinaryStrings(n, arr, i):
ifi == n:
printTheArray(arr, n)
return
arr[i] = 0
generateAllBinaryStrings(n, arr, i + 1)
arr[i] = 1
generateAllBinaryStrings(n, arr, i + 1)
if __name__ == "__main__":
n=4
arr = [None] * n
generateAllBinaryStrings(n, arr, 0)
Output:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
c) Write a python code to read dictionary values from the user. Construct a function
to invert its content. i.e., keys should be values and values should be keys
Source Code:
old_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69, 'G': 67, 'H': 23}
print()
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
exceptZeroDivisionError:
print("Denominator cannot be 0.")
exceptIndexError:
print("Index Out of Bound.")
6) Write a function called draw rectangle that takes a Canvas and a Rectangle as
arguments anddraws a representation of the Rectangle on the Canvas.
Source Code:
importtkinter as tk
master = [Link]()
def rectangle(event):
w.create_rectangle(event.x, event.y, event.x + 10, event.y + 10, fill="blue")
w = [Link](master, width=200, height=200)
[Link]()
[Link]("<Button-1>", rectangle)
[Link]()
Output:
b)Write a Python program to demonstrate the usage of Method Resolution Order
(MRO) in multiple levels of Inheritances.
Source Code:
class A:
defrk(self):
print(" In class A")
class B(A):
defrk(self):
print(" In class B")
class C(A):
defrk(self):
print("In class C")
# classes ordering
class D(B, C):
pass
r = D()
[Link]()
Output:
In class B
7.a) Write a Python code to merge two given file contents into a third file
# Open the first file for reading
open('[Link]', 'r') as file1:
# Read the contents of file1
file1_contents = [Link]()
Output:
Enter the file name 1: Pyhton
['Computer science Engineering\n', 'Elecronics and Communication
Engineering\n', 'Civil Engineering\n']
Enter the file name 2: c++
Computer science Engineering
Elecronics and Communication
EngineeringCivil Engineering
8.a) Import numpy, Plotpy and Scipy and explore their functionalities.
Source Code:
fromscipy import special #same for other modules
importnumpy as np
importnumpy as np
fromscipy import io as sio
array = [Link]((4, 4))
[Link]('[Link]', {'ar': array})
data = [Link](‘[Link]', struct_as_record=True)
data['ar']
Output:
array([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])
Source Code:
[Link] import cbrt
#Find cubic root of 27 & 64 using cbrt() function
cb = cbrt([27, 64])
#print value of cb
print(cb)
Output: array ([3., 4.])
Source Code:
[Link] import comb
#find combinations of 5, 2 values using comb(N, k)
com = comb(5, 2, exact = False, repetition=True)
print(com)
Output:
15.0
c) Write a program to implement Digital Logic Gates – AND, OR, NOT,
EX-OR
Source Code:
if a == 1 and b == 1:
return True
else:
return False
# Driver code
if __name__=='__main__':
print(AND(1, 1))
print("+---------------+----------------+")
print(" | AND Truth Table | Result |")
print(" A = False, B = False | A AND B =",AND(False,False)," | ")
print(" A = False, B = True | A AND B =",AND(False,True)," | ")
print(" A = True, B = False | A AND B =",AND(True,False)," | ")
print(" A = True, B = True | A AND B =",AND(True,True)," | ")
Output:
True
+---------------+----------------
print("+---------------+----------------+")
print(" | NAND Truth Table | Result |")
print(" A = False, B = False | A AND B =",NAND(False,False)," | ")
print(" A = False, B = True | A AND B =",NAND(False,True)," | ")
print(" A = True, B = False | A AND B =",NAND(True,False)," | ")
print(" A = True, B = True | A AND B =",NAND(True,True)," | ")
Output:
True
+---------------+----------------+
| NAND Truth Table | Result |
A = False, B = False | A AND B = True |
A = False, B = True | A AND B = True |
A = True, B = False | A AND B = True |
A = True, B = True | A AND B = False |
Source Code:
def OR(a, b):
if a == 1 or b ==1:
return True
else:
return False
# Driver code
if __name__=='__main__':
print(OR(0, 0))
print("+---------------+----------------+")
print(" | OR Truth Table | Result |")
print(" A = False, B = False | A OR B =",OR(False,False)," | ")
print(" A = False, B = True | A OR B =",OR(False,True)," | ")
print(" A = True, B = False | A OR B =",OR(True,False)," | ")
print(" A = True, B = True | A OR B =",OR(True,True)," | ")
Output:
False
+---------------+----------------+
d) Write a GUI program to create a window wizard having two text labels,
two text fields and two buttonsas Submit and Reset
Source Code:
importtkinterastk
defwrite_text():
parent=[Link]()
frame=[Link](parent)
[Link]()
text_disp=[Link](frame,
text="Hello",
command=write_text
text_disp.pack(side=[Link])
exit_button=[Link](frame,
text="Exit",
fg="green",
command=quit)
exit_button.pack(side=[Link])
[Link]()
Output:
AdditionalExperiments-beyondsyllabus:
Experiment-1:
DescribeaboutInstancevariableusingATMMachineClassProgram:
SOURCECODE:
classATM:
definit(self):
[Link]=0 #instanceVariableprint
"NewAccount Created"
defdeposit(self):
amount=input("Entertheamounttodeposit:"
)[Link]=[Link]+amount
print"NewBalanceis",[Link](self):a
mount=input("Enterthe amountto withdraw:")
[Link]<amount:
print"InsufficientBalance"else:
[Link]=[Link]-amount
print"NewBalanceis",[Link]
y(self):
print"TheBalanceis",[Link]=
ATM()
[Link]()
[Link]()
Output
NewAccountCreated
Entertheamountto deposit:1200
NewBalanceis1200Enter the amount
to withdraw: 950 New Balance is
250Enter the amounttowithdraw:120
Experiment-2:
DescribeaboutClassvariableusingRobotClass Program:
SOURCECODE:
classRobot:
what="Machine" #class
Variablename="Chitti"
version=1.0spee="1T
Hz"
memory="1ZB"
defupdate(cls):[Link]=2.0
[Link]="2THz"[Link]=
"2ZB"
r=Robot()
print""
print "Haii am a",[Link]
print"My Name is",[Link]
print"Version",[Link]
print"Speed",[Link]
print"Memory",[Link]
Output:
Haii am a
MachineMyName
isChitti
Version 1.0
Speed1THz
Memory1ZB
Haii am a
MachineMyNameis
Chitti
Version 2.0
Speed2THz
Memory2ZB
SchemeofEvaluation:
InternalAssessment
External Assessment
[Link]. Assessment of Evaluation in Marks
work
1 Writeup 20
2 Experimentation 20
3 Observation 10
4 Viva 10
Total 60
Marks
Reference Books:
TEXTBOOKS:
REFERENCEBOOKS: